首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >语用中的预期主表达式错误^0.8.0

语用中的预期主表达式错误^0.8.0
EN

Ethereum用户
提问于 2021-01-13 18:27:36
回答 1查看 2.3K关注 0票数 1

我试图从下面的链接中使用任何uint来字符串函数实现。

如何将uint转换为字符串?

如何将字符串转换为int

将uint转换为字符串

然而,在务实的solidity ^0.8.0中,编译器显示了以下错误:

ParserError:预期的主表达式.

有解决办法吗?

例如,此实现会产生该错误。

代码语言:javascript
复制
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;
}
EN

回答 1

Ethereum用户

回答已采纳

发布于 2021-01-14 12:56:01

不能直接将uint256转换为bytes1,但如果首先将其转换为uint8,则可以:

代码语言:javascript
复制
reversed[i++] = bytes1(uint8(48 + remainder));

完整的代码如下所示:

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/92262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档