mt logoMyToken
总市值:
0%
恐慌指数:
0%
币种:--
平台 --
ETH Gas:--
EN
USD
APP
Ap Store QR Code

Scan Download

Solidity编程语言:十六进制串、枚举enum

收藏
分享

十六进制串

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

另外在使用bytes4类型的固定长度字节数组进行引用时,hex长度不能超过引用类型的实际长度,比如bytes4 b = hex"AABBccddee"是无法编译的。

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; } }

枚举enum

Solidity中枚举类型与其他编程语言基本一样。我们来看一个例子,比如定义个季节的枚举。

pragma solidity >=0.4.0 <0.6.0;


contract  EgEnum{
    enum Season{Spring, Summer, Autumn, Winter}

function printSeason(Season s) public returns(Season) { return s; }

function test1() public returns(Season){ return printSeason(Season.Spring); }

function test2() public returns(uint){ uint s = uint(Season.Spring); return s; }

function test3() public returns(Season){ //Season s = Season(5);//越界 Season s = Season(3); return s; } }

  1. enum的实际类型是无符号整数,当枚举数量是0-127范围内,则enum是uint8类型的,如果是0-32,767范围内,则enum是uint16类型的,以次类推。
  2. 既然enum是uint类型,则可以进行类型转换,比如uint s = uint(Season.Spring)是将枚举Season类型转换在uint,当然也可以转成uint8,只要不越界就可以。同样Season s = Season(3)是将uint转成Season类型的。同样需要注意的是整数不要超过枚举的范围,比如Season的范围是0-3,如果将5转换成Season则会在运行进出现异常,而编译可以通过。
作者:感谢HPB 技术社区整理供稿。

汪晓明博客 http://wangxiaoming.com/

汪晓明:HPB芯链创始人,巴比特专栏作家。十余年金融大数据、区块链技术开发经验,曾参与创建银联大数据。主创区块链教学视频节目《明说》30多期,编写了《以太坊官网文档中文版》,并作为主要作者编写了《区块链开发指南》,在中国区块链社区以ID“蓝莲花”知名。

免责声明:本文版权归原作者所有,不代表MyToken(www.mytokencap.com)观点和立场;如有关于内容、版权等问题,请与我们联系。