Solidify實現一個智慧合約9(陣列和string之間的轉換關係)
阿新 • • 發佈:2018-12-15
固定大小位元組陣列之間的轉換
固定大小位元組陣列,我們可以通過bytes1~32來進行宣告,固定大小位元組陣列的長度不可變,內容不可修改。
pragma solidity ^0.4.4; contract Test { bytes5 public g = 0x6869736565; //hisee function getBytesLength() constant returns (uint) { return g.length; } function gTobytes2() constant returns (bytes2) { return bytes2(g); } function gTobytes10() constant returns (bytes10) { return bytes10(g); } }
說明:轉長的位元組陣列,後面填0。轉短的位元組陣列,截斷後面的。
固定大小位元組陣列轉動態大小位元組陣列
pragma solidity ^0.4.4; contract Test { bytes5 public b = 0x6869736565; //hisee function jingZhuanDong() constant returns (bytes) { bytes memory b1 = new bytes(b.length); for(uint i=0;i<b.length;i++){ b1[i] = b[i]; } return b1; } }
固定大小位元組陣列不能直接轉換為string
動態大小位元組陣列轉string
pragma solidity ^0.4.4; contract Test { bytes5 public b = 0x6869736565; //hisee bytes names = new bytes(2); bytes name = new bytes(b.length); function Test() { names[0]=0x68; names[1]=0x69; for(uint i=0;i<b.length;i++){ name[i] = b[i]; } } function namesToString() constant returns (string) { return string(names); } function nameToString() constant returns (string) { return string(name); } }
本身就是動態大小位元組陣列
固定大小位元組陣列轉string,需先轉動態位元組陣列後再轉string
pragma solidity ^0.4.4;
contract Test {
bytes5 public b = 0x6869736565; //hisee
function bytes32ToString(bytes32 x) constant returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for(uint i=0;i<32;i++){
byte char = byte(bytes32(uint(x)*2**(8*i)));//左移2的(8*i)次方,下同
// byte char = byte(bytes32(uint(x) << (8*i)));
if(char!=0){
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for(i=0;i<charCount;i++){
bytesStringTrimmed[i] = bytesString[i];
}
return string(bytesStringTrimmed);
}
}