【2022 元宇宙基础NFT之Solidity OOP编程第12篇】3分钟了解Solidity Types – 整型(Integer)
int/uint:
变长的有符号或无符号整型。变量支持的步长以8
递增,支持从uint8
到uint256
,以及int8
到int256
。需要注意的是,uint
和int
默认代表的是uint256
和int256
。
什么是有符号整型,什么是无符号整型
无符号整型(uint)是计算机编程中的一种数值资料型别。有符号整型(int)可以表示任何规定范围内的整数,无符号整型只能表示非负数(0及正数)。
有符号整型能够表示负数的代价是其能够存储正数的范围的缩小,因为其约一半的数值范围要用来表示负数。如:uint8
的存储范围为0 ~ 255
,而int8
的范围为-127 ~ 127
如果用二进制表示:
- uint8: 0b
00000000
~ 0b11111111
,每一位都存储值,范围为0 ~ 255 - int8:0b
11111111
~ ob01111111
,最左一位表示符号,1
表示负
,0
表示正
,范围为-127 ~ 127
支持的运算符
-
比较:
<=
,<
,==
,!=
,>=
,>
,返回值为bool
类型。 -
位运算符:
&
,|
,(^
异或),(~
非)。 -
数学运算:
+
,-
,一元运算+
,*
,/
,(%
求余),(**
次方),(<<
左移),(>>
右移)。
Solidity目前沒有支持double/float
,如果是 7/2
会得到3
,即无条件舍去。但如果运算符是字面量,则不会截断(后面会进一步提到)。另外除0会抛异常 ,我们来看看下面的这个例子:
一、加 +,减 -,乘 *,除 /
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Math {
function mul(int a, int b) pure public returns (int) {
int c = a * b;
return c;
}
function div(int a, int b) pure public returns (int) {
int c = a / b;
return c;
}
function sub(int a, int b) pure public returns (int) {
return a - b;
}
function add(int a, int b) pure public returns (int) {
int c = a + b;
return c;
}
}
如果用5除以0就会抛出异常。
call to Math.div errored: VM error: revert.
revert
The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.
二、求余 %
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.0;
contract Math {
function m(int a, int b) pure public returns (int) {
int c = a % b; // 10 % 3 -> 1
return c;
}
}
三、次方
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Math {
function m(int a, int b) pure public returns (int) {
int c = a % b; // 10 % 3 -> 1
return c;
}
}
四、与 &,| 或,非 ~,^ 异或
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Math {
function yu() pure public returns (uint) {
uint a = 3; // 0b0011
uint b = 4; // 0b0100
uint c = a & b; // 0b0000
return c; // 0
}
function huo() pure public returns (uint) {
uint a = 3; // 0b0011
uint b = 4; // 0b0100
uint c = a | b; // 0b0111
return c; // 7
}
function fei() pure public returns (uint8) {
uint8 a = 3; // 0b00000011
uint8 c = ~a; // 0b11111100
return c; // 252
}
function yihuo() pure public returns (uint) {
uint a = 3; // 0b0011
uint b = 4; // 0b0100
uint c = a ^ b; // 0b0111
return c; // 7
}
}
五、位移
温馨提示:此处内容已隐藏,您必须消耗1个积分后才能查看。 
或者

关注微信公众号: 程序咖元宇宙实验室
回复:程序咖巴士 ,获取验证码。
验证码:
验证码: