所以,我正在编写一个将数字转换为二进制的合约,当我想将数组的索引设置为数字时,编译器会抛出此错误:
TypeError: Type bytes memory is not implicitly convertible to expected type bytes1
这是我想做的代码的一个例子:
bytes memory _binary = new bytes(8);
uint r = 0;
//Loop and math
_binary[i] = abi.encodePacked(r);
return string(_binary);
抛出错误的_binary行,任何帮助都将是感激的。
abi.encodePacked
返回bytes
类型——一个动态长度的字节数组。
但_binary[i]
是bytes1
类型-长度为1的固定长度字节数组。(这可能有点令人困惑,没有"单个字节项",只有一个"单个字节数组"。)
所以你需要将值类型转换为bytes1
:
_binary[i] = bytes1(abi.encodePacked(r));