In this track: Write and read Solidity
advanced · 4 MIN READ

Signed versus unsigned integers

Negative values require a representation and range appropriate to the task.

LET’S PICTURE IT

A temperature can be below zero, while a count of tickets cannot ordinarily be negative.

SEE IT FOR YOURSELF
A valid counter call, step by stepStep 1 / 4
A valid counter call, step by stepFunction requestincrement()No argumentsBefore executionstored count0A local teaching example with a defined starting stateIncoming callCheck function dispatchCheck coded conditionsRules passConditions passContinue executionA failed check can revert insteadCalculation0 + 1Result: 1Storage writecount = 1Persists if call succeedsCalculating a local value and storing it are separate stepsPersistent statecount1Later readGetter reports 1No new incrementState, logs and browser display have different roles

This example begins with count zero and a request to call increment(). No real contract is deployed.

Animated local teaching model. No wallet, RPC or live blockchain data. Some labels and hashes are abbreviated for readability.

Unsigned ranges begin at zero

A uint of a given width covers non-negative integers up to its bit-defined maximum. Subtracting beyond zero normally fails in checked Solidity arithmetic.

Signed ranges include a negative half

An int type uses two’s-complement representation. For a width of n bits, its range is −2^(n−1) through 2^(n−1)−1. int8 therefore spans −128 through 127.

Casts need reasoning

Converting representation or narrowing a type is not a substitute for validating business meaning. Explicit conversions can have truncation or reinterpretation effects that deserve separate checks.

ABI words preserve type context

The same 32-byte bits can mean a large unsigned number or a negative signed value depending on the schema. A decoder needs the intended type, not just raw bytes.

Read the example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract LearningExample {
    function difference(int256 a, int256 b)
        external pure returns (int256)
    {
        return a - b;
    }
}

Checked arithmetic can still revert if the signed result exceeds its range.

QUICK CHECK · NO PRESSURE

What is the maximum int8 value?

Your progress stays in this browser.
Keep exploring the original referenceSolidity documentation ↗

Original explanations by EtherTools. Examples are educational and source-linked; this site is independent of the Ethereum Foundation. Our approach.