Conversions between types in Solidity
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.
- Automatic conversions, done by the compiler.
- Can do this when there is no loss of data, for example a
uint8can be automatically converted to
- Cannot do this when there might be loss of data. For example a
uint256cannot be automatically converted to
- Cannot convert between signed/not signed automatically (cannot go from
You can use explicit conversion, and even if you will lose data it will still convert.
For example you can go from a
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
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!
📙 Solidity Auditing online quiz
Learn how to audit smart contracts by looking at some example code and trying to find the bugs
⛽ Solidity Gas Optimizations Guide
How to optimize and reduce gas usage in your smart contracts in Solidity
🧪 Guide to testing with Foundry
Guide to adding testing for your Solidity contracts, using the Foundry and Forge tools
📌 Guide to UTXO
UTXO and the UTXO set (used by blockchains such as Bitcoin) explained
📐 Solidity Assembly Guide
Introduction guide to using assembly in your Solidity smart contracts
📦 Ethereum EOF format explained
Information explaining what the upcoming Ethereum EOF format is all about