Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 47 ยท Language Basics

Operators, Ether Units and Time Units

Learn every Solidity operator (arithmetic, comparison, logical, bitwise, assignment), the ** and % rules, and wei, gwei, ether and time units, with BigInt demos.

Once you have value types, the next step is to combine them. Solidity's operators look like the ones in C and JavaScript, but the details differ in ways that matter for money: division truncates, exponentiation is right-associative, bitwise operators work on fixed bit widths, and arithmetic is checked, so a mistake reverts instead of wrapping silently. Units such as ether and days are also operators of a kind: suffixes that multiply a number.

This lesson covers all the operator families, the precedence rules, and the two groups of unit suffixes. As before, Solidity is shown read-only and BigInt stand-ins let you try the rules. For what happens on overflow in depth, see Integers, Overflow and Checked Math.

Arithmetic operators

Operator Meaning Example (uint) Result
+ Addition 7 + 2 9
- Subtraction 7 - 2 5
* Multiplication 7 * 2 14
/ Division (truncating) 7 / 2 3
% Modulus (remainder) 7 % 2 1
** Exponentiation 2 ** 10 1024
SOLIDITY
uint256 a = 17;
uint256 b = 5;

uint256 quotient  = a / b;    // 3, the fraction is dropped
uint256 remainder = a % b;    // 2
uint256 power     = 2 ** 8;   // 256

Several rules are worth remembering:

  • Division truncates toward zero. There are no floating-point numbers, so 1 / 2 is 0. If you need fractions, scale first (multiply by 1e18, divide later) as shown in Integers, Overflow and Checked Math.
  • Division or modulo by zero reverts with a panic (error code 0x12). It is never silently zero or infinity.
  • % follows the sign of the left operand for signed integers: -7 % 3 is -1.
  • ** is right-associative. 2 ** 3 ** 2 means 2 ** (3 ** 2), which is 512, not 64. Add parentheses if you want to be explicit. 0 ** 0 is 1.
  • The result type of a ** b is the type of a. Writing 10 ** 18 with literals gives a literal that the compiler folds into a constant, which is why 10 ** 18 is free, while uint8(10) ** 3 overflows an 8-bit value (reverting since 0.8).
  • Unary minus is only allowed on signed integers, so -x for a uint is a compile error.

The shorthand assignment forms +=, -=, *=, /=, %= exist, as do ++ and -- (before or after a variable). x++ returns the old value, ++x the new one. On a uint holding its maximum, ++ reverts.

Relational (comparison) operators

==, !=, <, <=, > and >= compare two values of compatible types and produce a bool. You can compare integers, addresses (== and !=, plus ordering for equal-size values), bytesN values and enums. You cannot compare strings with ==; compare their hashes instead: keccak256(bytes(a)) == keccak256(bytes(b)).

SOLIDITY
bool isAdult   = age >= 18;
bool sameOwner = msg.sender == owner;
bool differs   = keccak256(bytes(a)) != keccak256(bytes(b));

Comparing numbers of different sizes is allowed when no information can be lost: a uint8 can be compared with a uint256 because it converts implicitly. Comparing a uint256 with an int256 is an error, because neither type can hold all values of the other; convert one side explicitly after checking its sign.

Logical operators

! (not), && (and) and || (or) work on bool. && and || short-circuit: if the left side already decides the result, the right side is not evaluated. This is both a gas saver and a safety tool.

SOLIDITY
if (user != address(0) && balances[user] > 0) {
    // balances[user] is only read if user is not the zero address
}

Put the cheap or most likely to fail check on the left. There is no and/or keyword and no truthiness: if (balance) does not compile, you must write balance != 0.

Bitwise operators

Bitwise operators work on the binary representation of integers and bytesN.

Operator Name Example (uint8) Result
& AND 12 & 10 (1100 & 1010) 8
| OR 12 | 10 14
^ XOR 12 ^ 10 6
~ NOT (flip every bit) ~uint8(12) 243
<< Shift left 1 << 3 8
>> Shift right 16 >> 2 4
SOLIDITY
uint256 flags = 0;
uint256 constant CAN_READ  = 1 << 0;   // 0001
uint256 constant CAN_WRITE = 1 << 1;   // 0010

flags |= CAN_READ | CAN_WRITE;         // set both
bool mayWrite = (flags & CAN_WRITE) != 0;
flags &= ~CAN_READ;                    // clear one bit

A few details: ~ flips every bit within the type's width, so ~uint8(12) is 243 but ~uint256(12) is a huge number. Shifts are by an unsigned amount. A left shift can push bits off the left edge: unlike *, a shift does not revert when bits are lost, and a shift by the type's width or more gives zero. Right shift of a signed negative value is an arithmetic shift (rounds toward negative infinity). Bit tricks are used for permission flags, packing several small values into one storage slot, and in gas-optimized libraries.

Conditional and other operators

The ternary operator cond ? a : b chooses between two expressions of the same type. delete x resets a variable to its default value. The comma-separated tuple form lets you destructure a return value: (uint256 a, ) = f();, where the empty slot skips a value. Parentheses group expressions as usual.

Precedence

From highest to lowest, the important levels are: postfix ++ --, unary (! ~ - delete ++x), **, then * / %, then + -, then << >>, then &, ^, |, then comparisons (< > <= >=), then == !=, then &&, then ||, then ?: and the assignments. Unlike C, bit operators bind tighter than comparison in Solidity, but do not rely on memory here: use parentheses whenever a line mixes families. (flags & CAN_WRITE) != 0 is both safe and readable.

Ether units

Amounts of ETH are stored in wei, the smallest unit, as plain integers. To avoid counting zeros, Solidity lets you attach a unit to a number literal:

Unit Value in wei Notes
wei 1 The base unit
gwei 10^9 Gas prices are quoted in gwei (also called shannon)
ether 10^18 What people call "one ETH"

Older names for the in-between sizes exist in the Ethereum world: kwei (babbage, 10^3), mwei (lovelace, 10^6), szabo (10^12) and finney (10^15), named after cryptographers and early contributors. The szabo and finney suffixes were removed from the language in version 0.7, so write 1 gwei or 1e15 instead. The suffix is only a multiplier: 2 ether is the integer 2000000000000000000, and 0.5 ether is 500000000000000000. You can write decimals on a literal as long as the final value is a whole number of wei; 1.5 gwei works, but 0.5 wei does not compile.

SOLIDITY
uint256 public constant PRICE = 0.01 ether;     // 10_000_000_000_000_000 wei

function buy() external payable {
    require(msg.value >= PRICE, "too little ETH");
}

Why does this matter beyond convenience? ETH has several roles: it pays for gas (fuel for transactions), rewards validators (the incentive that secures the network), and is held as an asset. Because the integer is in wei, there is no rounding error when you add or subtract amounts, and you avoid floating-point entirely. The trouble starts only when you divide, for example splitting 1 wei between three people leaves a remainder that you must handle on purpose. A tiny subdivision (wei) also lets you estimate gas costs accurately: a transaction costing 21,000 gas at 30 gwei costs 21000 * 30 gwei = 630,000 gwei = 0.00063 ether.

Time units

Time suffixes turn a number into seconds: seconds (1), minutes (60), hours (3600), days (86,400) and weeks (604,800). The unit years was removed in 0.5.0 because years are not all the same length, so a "year" suffix would be a trap.

SOLIDITY
uint256 public deadline = block.timestamp + 7 days;

function isOpen() public view returns (bool) {
    return block.timestamp < deadline;
}

Remember that block.timestamp is set by the block producer and can be off by a few seconds, so contracts should not depend on it for anything that needs second-level precision. Use it for periods of hours or days. See msg.sender, msg.value and Global Variables for the other block values.

Try it: operators on fixed-width integers

JavaScript BigInt has no width, so the helper below adds it back. It rejects results that do not fit (like Solidity 0.8's checked arithmetic), masks results of ~ and << to the type's width, and shows the right-associativity of **.

JS Checked arithmetic and bitwise operators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: unit conversion and gas cost

Units are only multipliers, so a converter is a few lines. This one uses the units Solidity still supports, plus the time suffixes, and works the gas example from above.

JS wei, gwei, ether and time units

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real: the operator families, the truncating division, the right-associative **, the revert-on-overflow behavior, the unit multipliers and the removal of szabo, finney and years follow Solidity 0.8. What is the stand-in: makeUint re-creates fixed-width integers on top of BigInt, and the gas fee uses a made-up gas price, not a live network figure.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 2 ** 3 ** 2 evaluate to in Solidity?

    ** is right-associative, so it is 2 ** (3 ** 2) = 2 ** 9 = 512. Use parentheses to make the intent clear.
  2. 2. What happens when you divide a uint by zero?

    Division and modulo by zero cause a Panic(0x12) and revert the whole call.
  3. 3. What is ~uint8(12)?

    ~ flips every bit within the type's width. 12 is 00001100, so the result is 11110011, which is 243. A uint cannot be negative.
  4. 4. How many wei is 1 gwei?

    gwei is 10^9 wei. ether is 10^18 wei. Gas prices are normally quoted in gwei.
  5. 5. Why was the years time unit removed?

    Leap years mean a year is not always 365 days, so a years suffix could silently produce the wrong number of seconds. Use days and do the math explicitly.

Summary

  • Arithmetic uses + - * / % **; division truncates, division or modulo by zero reverts, and ** is right-associative. Since 0.8 overflow also reverts.
  • Comparisons produce bool; strings must be compared by hash. && and || short-circuit and there is no truthiness.
  • Bitwise & | ^ ~ << >> work within the type's width and are used for flags and packing. Shifts never revert.
  • Use parentheses whenever a line mixes operator families.
  • wei, gwei and ether are multipliers for amounts of ETH (szabo and finney are gone); seconds, minutes, hours, days and weeks turn numbers into seconds (years is gone).

Next: reference types that live in memory and storage, in Strings, Bytes, Arrays and Structs.