Solidity
pragma solidity ^0.4.0;
contract demo {
string name = "chj";
function getName() view public returns(string) {
return name;
}
function setName(string _name) public {
name = _name;
}
// 相当于仅是一个普通函数,不会改变值,单节约 gas
function pureTest(string _name) pure public returns(string) {
return _name;
}
// 事实上它支持 c 语言一样的逻辑判断符
function judge() public returns(bool) {
bool a = false;
return a;
}
}
不加 view 这些玩意会被系统认为调用外部资源
pragma solidity ^0.4.0;
contract demo {
// int 与 uint 都是 256 位
int a = 12;
uint b = 12;
uint8 c = 12;
function add(uint a, uint b) pure public returns(uint) {
return a + b;
}
// 溢出的现象其实和 C 语言里的一样
function flow() view public returns(uint) {
return 256;
}
}
bytes 是固定长度字节数组
bytes1 是八位,其他类推,通常用 16 进制表示
固定长度数组
pragma solidity ^0.4.0;
contract demo {
// 注意:固定长度数组是不能修改的,类似于 Python 的元祖
// 0111 1010
bytes1 num1 = 0x7a;
// 0111 1010 0110 1000
bytes2 num2 = 0x7a68;
// 1
function getLength1() returns(uint) {
return num1.length;
}
// 2
function getLength2() returns(uint) {
return num2.length;
}
}
动态长度数组
pragma solidity ^0.4.0;
contract demo {
bytes public name = new bytes(2);
function InitName() {
name[0] = 0x7a;
name[1] = 0x68;
}
function getLength() view returns(uint) {
return name.length;
}
function changeName() {
name[0] = 0x88;
}
function changeLength() {
name.length = 5;
}
// 动态添加数据
function pushTest() {
name.push(0x99);
}
}
单引号和双引号没有区别
string 是特殊动态数组,utf8 类型
string 没有 Length 这个属性,因此不能获取它的长度
通过下标只能获取 Bytes 数据,不能将它强制转换为 string !!!
string 支持中文,但是注意,它是三个字节的
pragma solidity ^0.4.0;
contract demo {
string name = "zhangsan";
function getLength() view returns(uint) {
// 只能通过这种方式获取长度
return bytes(name).length;
}
function getByte() returns(bytes1) {
// 只能通过这种方式获取指定下标的数据
return bytes(name)[0];
}
function getName() returns(bytes) {
return bytes(name);
}
function setByte() {
bytes(name)[0] = 'L';
}
}s
固定长度字节数组的转换
pragma solidity ^0.4.0;
contract demo {
bytes3 name = 0x7a6865;
// 0x7a
function getBytes1() returns(bytes1) {
return bytes1(name);
}
// 0x7a68
function getBytes2() returns(bytes2) {
return bytes2(name);
}
// 0x7a6865
function getBytes3() returns(bytes3) {
return bytes3(name);
}
}
固定长度数组转动态长度数组
pragma solidity ^0.4.0;
contract demo {
bytes3 name = 0x7a6865;
function toDynamic() view returns(bytes) {
// 之前没有 memory 是因为声明在函数体外部
bytes memory newName = new bytes(name.length);
// 索引必须是 uint
for (uint i = 0; i < name.length; i++) {
newName[i] = name[i];
}
return newName;
}
}
bytes 转 string(动态长度数组转化为 string)
pragma solidity ^0.4.0;
contract demo {
bytes name = new bytes(2);
function Init() {
name[0] = 0x7a;
name[1] = 0x68;
}
function toStrin