是否有一种简单的方法可以将bytes32转换为bytes?
我正在尝试获取在bytes32变量中传递的字符串的长度,但是所有内容都返回32大小,这是有意义的。
但显式转换似乎不起作用:
bytes memory _tmpUsername = bytes(_username); // _username is of type bytes32 这会引发以下错误:
Explicit type conversion not allowed from "bytes32" to "bytes storage pointer"发布于 2018-08-06 17:35:25
从solidity@0.4.22开始,您可以使用abi.encodePacked()来实现它,这将返回bytes。例如;
contract C {
function toBytes(bytes32 _data) public pure returns (bytes) {
return abi.encodePacked(_data);
}
}发布于 2018-02-26 02:32:45
下面是一种将bytes32转换为字节的效率很低的方法(同时将额外的零字节移到右边)。
function bytes32ToBytes(bytes32 data) internal pure returns (bytes) {
uint i = 0;
while (i < 32 && uint(data[i]) != 0) {
++i;
}
bytes memory result = new bytes(i);
i = 0;
while (i < 32 && data[i] != 0) {
result[i] = data[i];
++i;
}
return result;
}发布于 2022-08-21 09:02:56
的回答
您可以使用bytes.concat而不是abi.encodePacked。
function toBytes(bytes32 data) public pure returns (bytes memory) {
return bytes.concat(data);
}我的理解是,bytes.concat最终将取代abi.encodePacked。
https://ethereum.stackexchange.com/questions/40920
复制相似问题