solidity智能合约[15]-fixtostring

solidity智能合约[15]-fixtostring

 2018-11-19  智能合约 solidity语法  solidity以太坊智能合约  4  评论 字数统计: 218(字) 阅读时长: 1(分)

固定字节数组转string

固定字节数组转换为string没有好的办法,必须要首先将固定字节数组转换为动态字节数组,再将动态字节数组转换为string

1
2
3
4
5
6
7
8
9
10
11
12
//bytes2  ->  bytes   ---->string
  function fixtostr(bytes32 _newname) pure public returns(string){


    bytes memory newName = new bytes(_newname.length);

    for(uint i = 0;i<newName.length;i++){
        newName[i] =  _newname[i];
    }

    return string(newName);
}

上面的函数传递0x6a6f的时候,返回的结果为"bytes32 newname": "0x6a6f000000000000000000000000000000000000000000000000000000000000
这显然不是我们想要的。这是由于新建的动态数组的长度为32的原因。下面对其进行改进:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function fixtostr2(bytes32 _newname) pure public returns(string){
  //计数
   uint count = 0 ;

   for(uint i = 0;i<_newname.length;i++){
       bytes1 ch = _newname[i];
       if(ch !=0){
           count++;
       }
   }

   bytes memory name2 = new bytes(count);

   for(uint j = 0;j<name2.length;j++){
       name2[j] = _newname[j];
   }
   return string(name2);
}

 

郑建勋(jonson)区块链工程师 & Web工程师

灾难总是接踵而至,这正是世间的常理。你以为只要哭诉一下,就会有谁来救你吗?如果失败了,就只能说明我不过是如此程度的男人。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值