温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

solidity智能合约[15]-fixtostring

发布时间:2020-07-14 14:02:06 阅读:192 作者:jonson_jackson 栏目:开发技术

固定字节数组转string

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

123456789101112
//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的原因。下面对其进行改进:

123456789101112131415161718
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);}
  • 本文链接: https://dreamerjonson.com/2018/11/19/solidity-15-fixtostring/

  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!

solidity智能合约[15]-fixtostring

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI