Solidity

Solidity Type Conversion

Solidity Type Conversion Main Tips

  • Normally, when an operator has been assigned to variables of different types, implicitly, the compiler will try to convert one of these operands to the other type. This is true for assignments as well.
  • When implicit conversion is not allowed, an explicit type connection can be enabled. This, however, is likelier to cause unexpected behavior.

Solidity Type Conversion Implicit Conversions

Normally, when an operator has been assigned to different types, implicitly, the compiler will try to convert one of these operands to the other type. This is true for assignments as well.

Generally, an implicit conversion from one value-type to another is possible when it makes sense semantically, with no information being lost: uint8 can be converted to to uint16, then uint128 to int256, however, int8 cannot be converted to uint256 (since uint256 cannot hold e.g. -1). Moreover, unsigned integers are convertible to bytes of a similar or larger size, but not vice-versa. Any type which can be converted to uint160 may also be converted into the type address.


Solidity Type Conversion Explicit Conversions

When implicit conversion is not allowed, an explicit type connection can be enabled. This, however, is likelier to cause unexpected behavior, so be careful.

In the example below you can see the code is used to convert a negative int8 into a uint type:

Example

int8 x = -3;
uint y = uint(x);

 

Try on Remix Try live on Hosting

Once this code is executed, x is going to have the value 0xfffff..fd ( equivalent to sixty four hex characters), that is -3 in the complement representation of two, of 256 bits.

When a type is converted into a smaller type explicitly, bits of higher-order get cut off:

Example

uint32 x = 0x12345678;
uint16 y = uint16(x); // y is going to be 0x5678 now

 

Try on Remix Try live on Hosting

Read previous post:
Solidity Operators Involving LValues

Solidity Operators Involving LValues Main Tips An LValue is a variable or something, which can have something assigned to it. There...

Close