我试图从下面的链接中使用任何uint来字符串函数实现。
然而,在务实的solidity ^0.8.0中,编译器显示了以下错误:
有解决办法吗?
例如,此实现会产生该错误。
function uintToString(uint v) public returns (string memory) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i); // i + 1 is inefficient
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - j - 1]; // to avoid the off-by-one error
}
string memory str = string(s); // memory isn't implicitly convertible to storage
return str;
}发布于 2021-01-14 12:56:01
不能直接将uint256转换为bytes1,但如果首先将其转换为uint8,则可以:
reversed[i++] = bytes1(uint8(48 + remainder));完整的代码如下所示:
function uintToString(uint v) public pure returns (string memory) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = bytes1(uint8(48 + remainder));
}
bytes memory s = new bytes(i); // i + 1 is inefficient
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - j - 1]; // to avoid the off-by-one error
}
string memory str = string(s); // memory isn't implicitly convertible to storage
return str;
}https://ethereum.stackexchange.com/questions/92262
复制相似问题