Basic type conversion in solidity (14) | Getting Started series
2017/4/29 posted in Solidity entry series
Click to view the original text for optimized typography.
- Implicit conversions
If an operator can support different types. The compiler implicitly attempts to convert the type of an operand to the type of another operand, with the same assignment.
In general, the semantics can be converted as long as there is no loss of information between value types. Let's look at an example of an integer conversion:
pragma solidity ^0.4.0;
Contract int{
function conversion () returns (UInt16) {
Uint8 a = 1;
Implicit conversions
UInt16 B = A;
return (b);
}
}
In the example above, we convert an uint8 variable a implicitly to UInt16. It also supports conversion to uint32,uint128 and uint256.
In addition, unsigned integers can be converted to the same, or larger, types of bytes. However, it is important to note that the conversion cannot be reversed. Because address is 20 bytes in size, it is the same as the int160 size.
pragma solidity ^0.4.0;
Contract inttoaddress{
function f () returns (UINT) {
uint160 i = 10;
Address addr = i;
return addr.balance;
}
}
In the example above, the uint160 I is converted to an address.
- An explicit conversion
The compiler does not implicitly convert the syntactically non-convertible type, at which point we are going through an explicit conversion, such as converting a signed integer to an unsigned integer.
pragma solidity ^0.4.0;
Contract explicitconversion{
function f () returns (int8) {
Uint8 a = 1;
//强制转换int8 b = int8(a);return b;
}
}
- Type inference
Sometimes we don't explicitly define a type for convenience. But because the compiler will automatically pick the most appropriate type, so will often leave pits, we look at this example:
pragma solidity ^0.4.4;
Contract test{
function A () returns (UINT) {
UINT count = 0;
for (var i = 0; i <; i++) {
count++;
if (count >= 2100) {
Break
}
}
return count;
}
}
You can think of the result of the above code running.
The result of the above code operation is actually 2100. The reason is that because the var i = 0 is defined by type inference, I is the actual type of uint8, so it will always loop, and if there is no count >= 2100 This judgment statement, this loop will never end.
- Some common conversion scenarios
UINT converted to bytes
To turn a uint into bytes, use assembly1.
function tobytes (uint256 x) returns (bytes b) {
b = new bytes (32);
assembly {Mstore (add (b, c), X)}
}
The above conversion may be the most efficient way.
String converted to bytes
The string can be displayed to bytes. However, if you want to switch to BYTES32, you may only use Assembly2.
pragma solidity ^0.4.0;
Contract stringtobytes{
function StringToBytesVer1 (string memory source) returns (bytes result) {
Return bytes (source);
}
function StringToBytesVer2 (string memory Source) returns (Bytes32 result) {
Assembly {
Result: = Mload (Add (source, 32))
}
}
}
Basic type conversions in solidity