🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Type Conversion

Type conversion is changing a value from one type into another type. Writing the new type name before a value, like uint256(x), converts that value.

Widening a uint8 into a uint256 keeps the value

A uint8 value fits easily inside a uint256. The widened value reads back exactly the same.

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

contract WidenBox {
    uint8 public small = 200;

    function widened() public returns (uint256) {
        return uint256(small);
    }
}

Narrowing a fitting uint256 into a uint8

A uint256 holding a small value narrows cleanly into a uint8. The value 100 fits, so nothing is cut.

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

contract NarrowBox {
    uint256 public big = 100;

    function narrowed() public returns (uint8) {
        return uint8(big);
    }
}

uint8(300) cuts the value down to 44

The value 300 does not fit in a uint8. The conversion cuts it down to 44 instead of failing.

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

contract CutBox {
    uint256 public big = 300;

    function cut() public returns (uint8) {
        return uint8(big);
    }
}

Example

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

contract ConvertBox {
    uint8 public small = 25;
    uint256 public fitting = 100;
    uint256 public big = 300;
    int256 public signedNumber = -3;

    function widened() public returns (uint256) {
        return uint256(small);
    }

    function narrowed() public returns (uint8) {
        return uint8(fitting);
    }

    function cut() public returns (uint8) {
        return uint8(big);
    }

    function signedAsUnsigned() public returns (uint256) {
        return uint256(signedNumber);
    }
}

Key points

  • Conversion: writing a type name before a value changes that value into the named type.
  • Widening: converting a smaller type into a bigger type keeps the value the same.
  • Narrowing: converting a bigger type into a smaller type makes room for fewer values.
  • Truncation: a narrowing conversion cuts a too-big value down instead of failing.
  • Cut value: uint8(300) reads back as 44, because the value was cut down to fit.
  • Negative conversion: converting an int that holds a negative into a uint wraps it into a huge number.

In this example, one contract shows all four conversions together. The widened function turns the uint8 value 25 into a uint256 with the same value. The narrowed function turns a fitting uint256 into a uint8. The cut function turns 300 into a uint8 and gets 44. The signedAsUnsigned function turns a negative int into a uint, and the negative value wraps into a huge number instead of failing.

Note

conversion never guesses, so the code must name the new type every time it narrows.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

What does uint8(300) give in Solidity?