隐式转换
发生场景
转换的标准
显式转换
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Demo {
/*
* uint / int 从小转大,在二进制左侧补零
* uint / int 从大转小,从右开始保留数据
*/
uint16 public u1 = 300;
uint32 public u2 = uint32(u1); // 300
uint8 public u3 = uint8(u1); // 44
int16 public u1 = 300;
int32 public u2 = int32(u1); // 300
int8 public u3 = int8(u1); // 44
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Demo {
/*
* bytes 从小转大,在二进制右侧补零
* bytes 从大转小,从左开始保留数据
*/
bytes3 public b1 = 0x616263; // 0x616263
bytes4 public b2 = bytes4(b1); // 0x61626300
bytes1 public b3 = bytes1(b1); // 0x61
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Demo {
bytes2 public b1 = 0x6162; // 0x6162
// 0x6162 => 110000101100010 => 01100010 => 98
uint8 public u1 = uint8(uint16(b1)); // 98
// 0x6162 => 0110000101100010 => 24930
uint32 public u2 = uint32(uint16(b1)); // 24930
// 0x6162 => 0x61 => 97
uint8 public u3 = uint8(bytes1(b1)); // 97
// 0x6162 => 0x61620000 => 1633812480
uint32 public u4 = uint32(bytes4(b1)); // 1633812480
uint16 public u5 = 24930;
// 24930 => 100100100100110000 => 01100010 => 0x62
bytes1 public b2 = bytes1(uint8(u5)); // 0x62
// 24930 => 0x6162 => 0x61
bytes1 public b3 = bytes1(bytes2(u5)); // 0x61
// 24930 => 100100100100110000 => 0...0100100100100110000 => 0x00006162
bytes4 public b4 = bytes4(uint32(u5)); // 0x00006162
// 24930 => 0x6162 => 0x61620000
bytes4 public b5 = bytes4(bytes2(u5)); // 0x61620000
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Demo {
bytes public b1 = hex"6162";
bytes1 public bn1 = bytes1(b1); // 0x61
bytes4 public bn4 = bytes4(b1); // 0x61620000
function test() external pure returns (bytes memory) {
bytes2 bn2 = 0x6162;
bytes memory tmp = new bytes(2);
for (uint8 i = 0; i < 2; i++) {
tmp[i] = bn2[i];
}
return tmp; // 0x6162
}
}
本文链接:
https://www.55geek.cn/index.php/archives/128/