# 隐式转换 Implicit Conversions

uint8 y;
uint16 z;
uint32 x = y + z;


# 显式转换 Explicit Conversions

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


uint32 a = 0x12345678;
uint16 b = uint16(a); // b will be 0x5678 now


uint16 a = 0x1234;
uint32 b = uint32(a); // b will be 0x00001234 now
assert(a == b);


bytes2 a = 0x1234;
bytes1 b = bytes1(a); // b will be 0x12


bytes2 a = 0x1234;
bytes4 b = bytes4(a); // b will be 0x12340000
assert(a[0] == b[0]);
assert(a[1] == b[1]);


bytes2 a = 0x1234;
uint32 b = uint16(a); // b will be 0x00001234
uint32 c = uint32(bytes4(a)); // c will be 0x12340000
uint8 d = uint8(uint16(a)); // d will be 0x34
uint8 e = uint8(bytes1(a)); // e will be 0x12


// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.5;

contract C {
bytes s = "abcdefgh";
function f(bytes calldata c, bytes memory m) public view returns (bytes16, bytes3) {
require(c.length == 16, "");
bytes16 b = bytes16(m);  // if length of m is greater than 16, truncation will happen
b = bytes16(s);  // padded on the right, so result is "abcdefgh\0\0\0\0\0\0\0\0"
bytes3 b1 = bytes3(s); // truncated, b1 equals to "abc"
b = bytes16(c[:8]);  // also padded with zeros
return (b, b1);
}
}


# 文字和基本类型之间的转换 Conversions between Literals and Elementary Types

## 整数类型

uint8 a = 12; // fine
uint32 b = 1234; // fine
uint16 c = 0x123456; // fails, since it would have to truncate to 0x3456

• NOTE

## 固定大小的字节数组

bytes2 a = 54321; // not allowed
bytes2 b = 0x12; // not allowed
bytes2 c = 0x123; // not allowed
bytes2 d = 0x1234; // fine
bytes2 e = 0x0012; // fine
bytes4 f = 0; // fine
bytes4 g = 0x0; // fine


bytes2 a = hex"1234"; // fine
bytes2 b = "xy"; // fine
bytes2 c = hex"12"; // not allowed
bytes2 d = hex"123"; // not allowed
bytes2 e = "x"; // not allowed
bytes2 f = "xyz"; // not allowed


# 参考资料

https://docs.soliditylang.org/en/latest/types.html#conversions-between-elementary-types