1.固定大小的数组之间的转化
pragma solidity ^0.4.6;
contract TestCharge{
bytes2 public b = 0x6c11;
// bytes 大小使用bytes32的32决定
function bLength() returns(uint){
return b.length;
}
function b2Bytes32() returns(bytes32){
return bytes32(b);//不够的后面补0,0x6c00000000000...
}
function b2Bytes1() returns(byte){
return bytes1(b);//多余的后面去掉,0x6c
}
}
2.固定大小的数组和动态大小数组转化
pragma solidity ^0.4.6;
contract TestCharge{
bytes2 public b = 0x6c11;
function charge() constant returns(bytes){
//return bytes(b); // 不能直接转化
bytes memory b1 = new bytes(b.length);
for(uint i = 0; i < b.length; i++){
b1[i] = b[i];
}
return b1;
}
}
3.动态字节数组转化string
pragma solidity ^0.4.6;
contract TestCharge{
bytes9 name9 = 0x6c1112;
bytes name = new bytes(2);
function TestCharge(){
name[0] = 0x6c;
name[1] = 0x99;
}
function name9toString() returns(string){
// return string(name9);
return string(name);
}
}
4.固定大小字节数组转化string
先转化for循环转化为动态大小数组,然后转化为string
function bytes32toString(bytes32 b32) constant returns(string){
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for(uint j = 0; j < 32; j++){
byte char = byte(bytes32(uint(b32) * 2 **(8*j)));
if(char != 0){
bytesString[charCount] = char;
charCount ++;
}
}
bytes memory r = new bytes(charCount);
for(j = 0 ; j < charCount; j++){
r[j] = bytesString[j];
}
return string(r);
}