Solidify实现一个智能合约9(数组和string之间的转换关系)

固定大小字节数组之间的转换

固定大小字节数组,我们可以通过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);
  }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值