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;
}
}
- enum的实际类型是无符号整数,当枚举数量是0-127范围内,则enum是uint8类型的,如果是0-32,767范围内,则enum是uint16类型的,以次类推。
- 既然enum是uint类型,则可以进行类型转换,比如uint s = uint(Season.Spring)是将枚举Season类型转换在uint,当然也可以转成uint8,只要不越界就可以。同样Season s = Season(3)是将uint转成Season类型的。同样需要注意的是整数不要超过枚举的范围,比如Season的范围是0-3,如果将5转换成Season则会在运行进出现异常,而编译可以通过。
汪晓明博客 http://wangxiaoming.com/
汪晓明:HPB芯链创始人,巴比特专栏作家。十余年金融大数据、区块链技术开发经验,曾参与创建银联大数据。主创区块链教学视频节目《明说》30多期,编写了《以太坊官网文档中文版》,并作为主要作者编写了《区块链开发指南》,在中国区块链社区以ID“蓝莲花”知名。
POPCAT, PNUT, And PENGU Price Prediction After Robinhood Listing Hype
The post POPCAT, PNUT, And PENGU Price Prediction After Robinhood Listing Hype appeared first on Coi...
Pi Network Faces Pressure as KYC Deadline Closes In, Whales Pick Up Web3 Mobile Competitor Trading at $0.0045
The post Pi Network Faces Pressure as KYC Deadline Closes In, Whales Pick Up Web3 Mobile Competitor ...
XRP Price Prediction: Can XRP Grasp $5 as Democrats Try to Stop Crypto Reserve Plan
The post XRP Price Prediction: Can XRP Grasp $5 as Democrats Try to Stop Crypto Reserve Plan appeare...