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

2019-08-15 532 技术

十六进制串

十六进制串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“蓝莲花”知名。

币币情登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。文章内容仅供参考,不构成投资建议。投资者据此操作,风险自担。

交易平台最新公告查看更多>
成交额排行榜
  • 交易所
  • 币种
排名 交易所 成交额
1 币安网币安网 ¥8,223.32亿
2 欧易OKX欧易OKX ¥3,317.27亿
3 HTXHTX ¥601.24亿
4 CoinbaseCoinbase ¥157.00亿
5 芝麻开门芝麻开门 ¥2,273.23亿
6 BitgetBitget ¥2,265.47亿
7 BybitBybit ¥2,743.70亿
8 Crypto.comCrypto.com ¥529.62亿
9 BitfinexBitfinex ¥26.50亿
10 抹茶抹茶 ¥2,114.82亿