Solidity编程语言(10)--十六进制串

个人觉得十六进制串hex并不是一种Solidity的数据类型,因为你无法将hex作为一个类型去使用。
当把hex加到字面量前的时候,其作用就是限定了字面量的数据格式,必须是偶数位的[0-9a-fA-F]的字符串。这样当使用特定的数据类型去引用hex串的时候,隐式的会进行转换。比如string memory h = hex”010A31”,转换后的字符串h实际内容是\u0001\n1
另外在使用bytes4类型的固定长度字节数组进行引用时,hex长度不能超过引用类型的实际长度,比如bytes4 b = hex”AABBccddee”是无法编译的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
pragma solidity >=0.4.0 <0.6.0;

contract EgHex{
function test() public returns(string memory){
string memory h = hex"010A31";
//string memory h = hex"010G"
return h;
}

function test1() public returns(string memory){
string memory h = hex"010A";
return h;
}

function test2() public returns(bytes4){
//bytes4 b = hex"AABBccddee";
bytes4 c = hex"AABB";
bytes4 b = hex"AABBccdd";
return b;
}

function test3() public returns(bytes memory){
bytes memory b = hex"AABBccdd";
return b;
}
}