目录

十六进制字面量

优质
小牛编辑
137浏览
2023-12-01

十六进制字面量,以关键字hex打头,后面紧跟用单或双引号包裹的字符串。如hex"001122ff"。在内部会被表示为二进制流。通过下面的例子来理解下是什么意思:

pragma solidity ^0.4.0;
contract HexLiteral{
    function test() returns (string){
      var a = hex"001122FF";
      //var b = hex"A";
      //Expected primary expression
      
      return a;
  }
}

由于一个字节是8位,所以一个hex是由两个[0-9a-z]字符组成的。所以var b = hex"A";不是成双的字符串是会报错的。

转换

十六进制的字面量与字符串可以进行同样的类似操作:

pragma solidity ^0.4.0;
contract HexLiteralBytes{
    function test() returns (bytes4, bytes1, bytes1, bytes1, bytes1){
      bytes4 a = hex"001122FF";
      return (a, a[0], a[1], a[2], a[3]);
  }
}

可以发现,它可以隐式的转为bytes,上述代码的执行结果如下:

Result: "0x001122ff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011000000000000000000000000000000000000000000000000000000000000002200000000000000000000000000000000000000000000000000000000000000ff00000000000000000000000000000000000000000000000000000000000000"
Transaction cost: 21857 gas. 
Execution cost: 585 gas.
Decoded: 
bytes4: 0x001122ff
bytes1: 0x00
bytes1: 0x11
bytes1: 0x22
bytes1: 0xff