Solidity 智能合约开发语言·数据类型

简介: int/uint:变长的有符号或无符号整型。变量支持的步长以8递增,支持从uint8到uint256,以及int8到int256。需要注意的是,uint和int默认代表的是uint256和int256。

本文节选自电子书《Netkiller Blockchain 手札》

 

Netkiller Blockchain 手札

本文作者最近在找工作,有意向致电 13113668890

Mr. Neo Chan, 陈景峯(BG7NYT)


中国广东省深圳市龙华新区民治街道溪山美地
518131
+86 13113668890

<netkiller@msn.com>

文档始创于2018-02-10

版权 © 2018 Netkiller(Neo Chan). All rights reserved.

 

版权声明

转载请与作者联系,转载时请务必标明文章原始出处和作者信息及本声明。

http://www.netkiller.cn
http://netkiller.github.io
http://netkiller.sourceforge.net
微信订阅号 netkiller-ebook (微信扫描二维码)
QQ:13721218 请注明“读者”
QQ群:128659835 请注明“读者”

 

 

4.5. 数据类型

4.5.1. 数值型

int/uint:变长的有符号或无符号整型。变量支持的步长以8递增,支持从uint8到uint256,以及int8到int256。需要注意的是,uint和int默认代表的是uint256和int256。

有符号整型能够表示负数的代价是其能够存储正数的范围的缩小,因为其约一半的数值范围要用来表示负数。如:uint8的存储范围为0 ~ 255,而int8的范围为-127 ~ 127

支持的运算符:



比较:<=,<,==,!=,>=,>,返回值为bool类型。

位运算符:&,|,(^异或),(~非)。

数学运算:+,-,一元运算+,*,/,(%求余),(**次方),(<<左移),(>>右移)。
 

小数由"."组成,在他的左边或右边至少要包含一个数字。如"1.",".1","1.3"均是有效的小数。

4.5.1.1. 加 +,减 -,乘 *,除 / 运算演示

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract Math {

  function mul(int a, int b) public pure returns (int) {

      int c = a * b;
      return c;
  }

  function div(int a, int b) public pure  returns (int) {

      int c = a / b;
      return c;
  }

  function sub(int a, int b) public pure  returns (int) {
      
      return a - b;
  }

  function add(int a, int b) public pure  returns (int) {

      int c = a + b;
      return c;
  }
}

4.5.1.2. 求余 %

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract Math {

  function m(int a, int b) public pure returns (int) {

      int c = a % b;
      return c;
  }
}

4.5.1.3. 幂运算

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract Math {

  function m(uint a, uint b) public pure returns (uint) {

      uint c = a**b;
      return c;
  }

}

4.5.1.4. 与 &,| 或,非 ~,^ 异或

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract Math {

  function yu() public pure returns (uint) {

      uint a = 3; // 0b0011
      uint b = 4; // 0b0100
    
      uint c = a & b; // 0b0000
      return c; // 0
  }

  function huo() public pure returns (uint) {

      uint a = 3; // 0b0011
      uint b = 4; // 0b0100
    
      uint c = a | b; // 0b0111
      return c; // 7
  }

  function fei() public pure returns (uint8) {

      uint8 a = 3; // 0b00000011
      uint8 c = ~a; // 0b11111100
      return c; // 0
  }
  
  function yihuo() public pure returns (uint) {

      uint a = 3; // 0b0011
      uint b = 4; // 0b0100
    
      uint c = a ^ b; // 0b0111
      return c; // 252
  }
}

4.5.1.5. 位移

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn

contract Math {

  function leftShift() public pure returns (uint8) {

      uint8 a = 8; // 0b00001000
      uint8 c = a << 2; // 0b00100000
      return c; // 32
  }

  function rightShift() public pure returns (uint8) {

      uint8 a = 8; // 0b00001000
      uint8 c = a >> 2; // 0b00000010
      return c; // 2
  }

}



a << n 表示a的二进制位向左移动n位,在保证位数没有溢出的情况下等价于 a乘以2的n次方。
a >> n 表示a的二进制位向右移动n位,在保证位数没有溢出的情况下等价于 a除以2的n次方。
 

4.5.2. 字符串

string 字符串类型,字符串可以通过""或者''来定义字符串的值

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract StringTest {

    string name;
    
    function StringTest() public{
        name = "default";
    }
    function setName(string _name) public{
        name = _name;
    }
    function getName() public view returns(string){
        return name;
    }
}

4.5.2.1. 获取字符串长度

在 Solidity 中想获得字符串长度必须转成 bytes 类型然后使用 length 属性获得。bytes(string).length

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract StringTest {
    
    
    string public name = "http://www.netkiller.cn";
    

    function nameBytes() public constant returns (bytes) {
        
        return bytes(name);
    }
    
    function nameLength() public constant returns (uint) {
        
        return bytes(name).length;
    }

    function length(string _name) public pure returns (uint) {
        
        return bytes(_name).length;
    }
    
}
[提示] 提示

注意:汉字采用UTF8编码,一个汉字等于3个字节,当你使用 length("景峯") 测试时会返回长度 6。

4.5.3. 布尔(Booleans)

bool: 可能的取值为常量值true和false。支持的运算符:

! 逻辑非

&& 逻辑与

|| 逻辑或

== 等于

!= 不等于

bool a = true;
bool b = !a;

// a == b -> false
// a != b -> true
// a || b -> true
// a && b -> false

4.5.4. 字节类型

bytes names = "netkiller"
bytes9 _names = "netkiller";
bytes(name)[0] = 0xFF;

bytes memory _tmp = new bytes(3);
_tmp[0] = 0x4e;
_tmp[1] = 0x65;
_tmp[2] = 0x6f;
pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract BytesTest {
    
    bytes names = "netkiller";
    
    function get() public view returns (bytes) {
        
        return names;
    }
    function getBytes2() public pure returns (bytes2) {
        bytes9 _names = "netkiller";
        return bytes2(_names);
    }
    function bytesToString() public constant returns (string) {
        
        return string(names);
    }
   
    function copyBytes(bytes b) public pure returns (bytes) {
       
       bytes memory tmp = new bytes(b.length);
       
       for(uint i = 0; i < b.length; i++) {
           
           tmp[i] = b[i];
       }
       
       return tmp;
    }
    
    function bytesToString2() public pure returns (string) {
        bytes memory _tmp = new bytes(3);
        _tmp[0] = 0x4e;
        _tmp[1] = 0x65;
        _tmp[2] = 0x6f;
        return string(_tmp);
    }
   
}

.length可以动态修改字节数组的长度

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract BytesTest2 {
    
    // 初始化一个两个字节空间的字节数组
    bytes public array = new bytes(2);
    
    // 设置修改字节数组的长度
    function setLength(uint _len) public {
        array.length = _len;
    }
    
    // 返回字节数组的长度
    function getLength() constant public returns (uint) {
        return array.length;
    }
    
    // 往字节数组中添加字节
    function pushArray(byte _tmp) public{
        array.push(_tmp);
    }
    
}

4.5.5. 数组

//创建一个memory的数组
	uint[] memory a = new uint[](7);
	
	uint[] x = [uint(1), 3, 4];
	
    bytes memory b = new bytes(10);

二维数组

uint [2][3] T = [[1,2],[3,4],[5,6]];
pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract ArrayTest {
    
    uint [] array = [1,2,3,4,5];
    
    // 通过for循环计算数组内部的值的总和
    function sum() constant public returns (uint) {
        uint num = 0;
        for(uint i = 0; i < array.length; i++) {
            num = num + array[i];
        }
        return num;
    }
    
    function sumNumbers(uint[] _numbers) public pure returns (uint) {
        uint num = 0;
        for(uint i = 0; i < _numbers.length; i++) {
            num = num + _numbers[i];
        }
        return num;
    }
    
}

4.5.5.1. length

.length 属性是活动数组的尺寸

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract ArrayLength {
    
    uint [] array = [1,2,3,4,5];
    
    function getLength() public constant returns (uint) {
        
        return array.length;
    }
    
}

4.5.5.2. push() 方法

通过 push 可以向数组中添加数据

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract ArrayLength {
    
    uint [] array = [1,2,3,4,5];
    
    function pushArray() public {
        
        array.push(6);
    }
    
    function getLength() public constant returns (uint) {
        
        return array.length;
    }
    
}

4.5.6. 枚举类型

State 就是一个自定义的整型,当枚举数不够多时,它默认的类型为uint8,当枚举数足够多时,它会自动变成uint16,枚举下标定义从左至右从零开始。

New=0, Pending=1, Done=2, Deleted=3

访问枚举方式 State.New 实际等于数字 0

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract EnumTest {
    enum State { New, Pending, Done, Deleted }
    State state = State.New;

    function set(State _state) public {
        state = _state;
    }

    function get() constant public returns (State) {
        return state;
    }

}

枚举用来定义状态

pragma solidity ^0.4.0;

contract Purchase {
    enum State { Created, Locked, Inactive } // Enum
}

4.5.7. 结构体

定义结构体

struct Voter {
        uint weight; // weight is accumulated by delegation
        bool voted;  // if true, that person already voted
        address delegate; // person delegated to
        uint vote;   // index of the voted proposal
    }

    // This is a type for a single proposal.
    struct Proposal {
        bytes32 name;   // short name (up to 32 bytes)
        uint voteCount; // number of accumulated votes
    }

演示例子

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract Students {
    
    struct Person {
        string name;
        uint age;
        uint class;
        
    }

    Person person = Person("Neo",18,1);

    function getPerson() public view returns(string){
        return person.name;
    }
}

4.5.8. address

address public minter;

下面是一个获得账号余额的例子。

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract AddressTest{
    
    function getBalance(address _addr) public constant returns (uint){
        return _addr.balance;
    }

}

4.5.8.1. payable

4.5.8.2. .value()

4.5.8.3. .gas()

4.5.9. mapping

mapping 就是图数据结构,由 key 和 value 组成。

pragma solidity ^0.4.20;
//Author: netkiller <netkiller@msn.com>
//Home: http://www.netkiller.cn
contract MappingExample {
    
    mapping(uint => string) map;

    function put(uint key, string value) public {
        map[key] = value;
    }
    
    function get(uint key) constant public returns (string) {
        return map[key];
    }
}
相关文章
|
5月前
|
人工智能 供应链 安全
2026 年全球网络安全威胁态势与关键技术防御研究
本文基于Security Affairs 2026年第576期情报,系统分析Linux无文件远控(QLNX)、Dirty Frag内核提权、AI供应链投毒、Bluekit工业化钓鱼及关键基础设施混合攻击等新型威胁,揭示其内存化、智能化、武器化趋势;提出漏洞治理、供应链管控、钓鱼防御、终端加固、应急响应“五位一体”纵深防御框架,并提供可复现代码与工程化方案。(239字)
982 6
|
7月前
|
人工智能 安全 Linux
AI龙虾🦞真·喂饭级教程,OpenClaw阿里云/本地部署、配置百炼API+Skill接入及新手避坑手册
2026年初,OpenClaw(Clawdbot)凭借轻量化的本地AI操作系统属性迅速成为技术领域的热门工具,其72小时斩获60000+ GitHub Stars、星标数突破22万的成绩,印证了市场对可落地的AI自动化工具的需求。但多数新手在部署后难以发挥其核心价值,核心原因在于未掌握其Skills生态系统的使用逻辑。如果说大模型是OpenClaw的"大脑",那么Skills就是让其从"只会聊天"升级为"能落地干活"的"超级双手"。本文将从OpenClaw Skills核心原理出发,完整讲解2026年新手零基础下阿里云云端部署、MacOS/Linux/Windows11本地部署流程,以及阿里云
1003 1
|
12月前
|
存储 弹性计算 人工智能
阿里云渠道商:云文件存储 NAS是什么?
阿里云NAS提供云端共享存储,多台服务器可同时访问同一文件,解决版本混乱难题。支持跨地域挂载、自动备份与按需付费,适用于团队协作、数据共享等场景,开箱即用,免运维,助力企业高效上云。
|
12月前
|
敏捷开发 前端开发 测试技术
测试之道:重构你的测试策略 - 测试金字塔模型
测试之道:重构你的测试策略 - 测试金字塔模型
857 118
|
9月前
|
弹性计算
阿里云账号注册、实名认证及免费云产品申请流程
阿里云账号注册、实名认证及免费云产品申请流程 1. 打开阿里云官网。 2. 点击网页右上角的“注册”按钮。 3. 注册方式支持手机短信验证码注册、支付宝注册、淘宝注册和钉钉注册四种。 4. 若选择手机号注册,需输入手机号并点击“获取验证码”,随后将手机收到的6位数字验证码输入,即可完成注册。
1803 6
|
9月前
|
SQL 人工智能 分布式计算
轻松体验MaxCompute SQL AI:用SQL调用大模型
本报告通过三步实践演示如何用SQL调用大模型:领取MaxCompute资源、创建项目与测试表、使用AI_TEXT_COMPLETE函数实现文本摘要和情感分析。全程无需复杂代码,仅用标准SQL即可在数据环境中直接调用AI能力,显著降低应用门槛,提升分析效率,验证了SQL+AI融合处理文本的可行性。
288 8
|
10月前
|
人工智能 达摩院 安全
迈向云+数据中心的国产 CPU 新引擎,龙蜥大会 RISC-V 分论坛回顾一览
本论坛成为高效的技术交流与合作平台,充分展示了 RISC-V 架构在服务器、边缘计算等高性能场景的商业化落地,助力构建开放共赢的算力新生态。
|
人工智能 自动驾驶 大数据
“AI再聪明,也得靠大数据喂饱它”:聊聊大数据与人工智能的双剑合璧
“AI再聪明,也得靠大数据喂饱它”:聊聊大数据与人工智能的双剑合璧
650 2
|
人工智能 运维 架构师
技能革命3.0时代:云计算就业岗位有哪些?
本文探讨云计算就业市场的深层逻辑,从岗位体系、AI赋能及技术局限性应对策略三方面解析。云计算岗位涵盖基础设施、平台服务、数据智能与应用创新四层,需复合型能力;AI不仅提供技术工具,还推动教育范式变革,助力跨界融合;面对技术局限,分步验证与经验洞察双管齐下。未来就业将向技能多元化、自主性增强和社会价值再定义方向进化,强调个体能力生态的持续成长。
1602 33
|
Kubernetes Cloud Native Serverless
OpenKruise v1.8版本解读:解锁云原生应用管理的无限可能
OpenKruise在2025年2月发布了最新的1.8版本。此版本带来了诸多重要的更新与增强,致力于进一步提升云原生应用管理的效率、弹性和可靠性。