In this article, we will explore the different types of conversions that are available in Solidity and how they can be used.
In Solidity, both explicit and implicit conversions are supported.
In the Solidity compiler, implicit conversion is allowed between two data types as long as it is not possible to perform implicit conversions and no information is lost.
It can be seen that uint8 can be converted to uint16, but int8 can be converted to uint256, as int8 can contain negative values, which are not allowed in uint256.
This article discusses the following conversions:
- Implicit Conversions.
- Explicit Conversions.
- Conversions between Literals and Elementary Types.
Solidity Conversions Implicit
They occur automatically when variables of one type are assigned to variables of another type.
For instance, it is possible to implicitly convert an integer into a fixed point number or a string.
A built-in function such as uint() or int() performs these operations.
Solidity provides the following syntax for some of the most common conversion function:
int() to uint():
The given code converts the integer to an unsigned integer():
uint() to int()
The implicit conversion from uint() to int() can be done as follow:
string to bytes()
The string can be converted to bytes using implicit conversion as follow:
Conversions that are explicitly performed by the developer are known as explicit conversions.
In situations where you cannot rely on implicit conversions, these conversions are necessary.
It is also necessary to use explicit conversions when you are performing operations on variables that are distinct to each other.
The constructor syntax allows us to explicitly convert data types from one to another.
int8 to uint:
The explicit conversion from int8 to uint can be done as:
uint32 to uint16:
To convert uint32 to uint16, do consider the example below:
uint16 to uint32:
In order to convert uint16 to uint32,refer to the example below:
bytes2 to bytes1:
The following example shows the conversion of bytes2 to byte1:
bytes1 to bytes2:
If you want to convert bytes to bytes2, you can follow the given example:
bytes2 to bytes4:
The given example converts bytes2 to bytes4:
Solidity mappings offer a powerful way to store and retrieve key-value pairs efficiently.
Smart contracts use mappings in a variety of ways, such as tracking balances, tracking ownership, and storing data in a decentralized way.