New to blockchain software development? Read my beginners guide here

Conversions between types in Solidity

Created on May 2022 β€’ Tags: guidesethereumsolidity

Explanation about how Solidity will implicitly or explicitly convert between data types


Table of Contents for Conversions between types in Solidity


There are quite a few data types in Solidity, and it is often useful to convert between them (such as a uint8 to a uint160. Sometimes it can be automatically converted, sometimes you have to be explicit and tell the compiler how you want to convert between the types.

Implicit conversions

  • Automatic conversions, done by the compiler.
  • Can do this when there is no loss of data, for example a uint8 can be automatically converted to uint32
  • Cannot do this when there might be loss of data. For example a uint256 cannot be automatically converted to uint8.
  • Cannot convert between signed/not signed automatically (cannot go from uint8 to int32 for example).

Explicit conversions

You can use explicit conversion, and even if you will lose data it will still convert.

For example you can go from a uint256 to uint8. The first 248 bits will be discarded (the higher order bits are removed from the left side).

If you convert to a larger type, it gets 0 padded on the left (e.g. going from uint8 -> uint256). This is the same as what happens implicitly.

If you try and convert between signed numbers, it will do the conversion but keep the twos-compliment bit.

int256 signedValue = -10;

uint256 unsignedValue = uint256(signedValue); // if you output this, as a uint256 it comes out at 115792089237316195423570985008687907853269984665640564039457584007913129639926 (due to the flipped bit for negative from the `int256`

Spotted a typo or have a suggestion to make this crypto dev article better? Please let me know!

See all posts (70+ more)

See all posts (70+ more)

Was this post helpful? πŸ“§

If you liked this content and want to receive emails about future posts like this, enter your email. I'll never spam you.

Or follow me on @CryptoGuide_Dev on twitter

By using this site, you agree that you have read and understand its Privacy Policy and Terms of Use.
Use any information on this site at your own risk, I take no responsibility for the accuracy of safety of the information on this site.