Solidify實現一個智慧合約8(動態大小位元組陣列)
阿新 • • 發佈:2018-12-15
動態大小位元組陣列
string是一個動態尺寸的UTF-8編碼字串,它其實是一個特殊的可變位元組陣列,string是引用型別,而非值型別。
bytes動態位元組陣列,引用型別。
常規字串string轉換為bytes
string字串中沒有提供length方法獲取字串長度,也沒有提供方法修改某個索引的位元組碼,不過我們可以將string轉換為bytes,再呼叫length方法獲取位元組長度,當然可以修改某個索引的位元組碼。
原始碼
pragma solidity ^0.4.4; contract Test { bytes5 public g = 0x6869736565; //hisee string public name = "hisee"; function getBytesLength() constant returns (uint) { return g.length; } function nameBytes() constant returns (bytes) { return bytes(name); } function nameLength() constant returns (uint) { return bytes(name).length; } function setNameFirstByte(bytes1 z) { bytes(name)[0] = z; } }
漢字字串或特殊字串的轉換為bytes
特殊字元
pragma solidity ^0.4.4; contract Test { string public name = "hi!+&^%"; //7個字元 function nameBytes() constant returns (bytes) { return bytes(name); //0x6869212b265e25 } function nameLength() constant returns (uint) { return bytes(name).length; // 7 } }
每一個特殊字元都對應一個位元組。
中文字串
pragma solidity ^0.4.4; contract Test { string public name = "小白不百"; //4個漢字 function nameBytes() constant returns (bytes) { return bytes(name); //0xe5b08fe799bde4b88de799be } function nameLength() constant returns (uint) { return bytes(name).length; // 12 } }
一個漢字佔3個位元組。
建立bytes位元組陣列
pragma solidity ^0.4.4;
contract Test {
bytes public name = new bytes(1);//設定初始大小為1位元組
function setNameLength(uint length) {
name.length = length;
}
function nameLength() constant returns (uint) {
return name.length;
}
function setIndexByte(byte data,uint index) {
name[index] = data;
}
function clearByte(){
//name.length=0;
delete name; //兩種方法均可清空
}
}
可變位元組陣列的長度可變,內容可變。
bytes可變陣列length和push兩個函式的使用案例
pragma solidity ^0.4.4;
contract Test {
bytes public name = new bytes(1); //設定初始大小為1位元組
function setNameLength(uint length) {
name.length = length; //修改長度
}
function nameLength() constant returns (uint) {
return name.length; //獲取長度
}
}
pragma solidity ^0.4.4;
contract Test {
bytes public name = new bytes(2);//設定初始大小為2位元組
function setNameLength(uint length) {
name.length = length;
}
function nameLength() constant returns (uint) {
return name.length;
}
function pushByte(byte data) {
name.push(data);
}
}
push是增加一個位元組,陣列長度也會增加。