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);
  }
}

Solidify实现一个智能合约9(数组和string之间的转换关系)_第1张图片

说明:转长的字节数组,后面填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

固定大小字节数组不能直接转换为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

本身就是动态大小字节数组

固定大小字节数组转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

 

你可能感兴趣的:(区块链智能合约)