0

I am trying to use any of the uint to string function implementations from the below links.

How to convert uint to string in solidity?

How to convert string to int

Conversion of uint to string

However in pragma solidity ^0.8.0 the compiler show the following error:

ParserError: Expected primary expression.

Is there a workaround?

This implementation for example produces that error

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;
}
4
  • 1
    Please provide your contract code.
    – Morten
    Jan 13 at 19:09
  • HI @Morten, I updated the description with an example that show that error on remix compiler ^0.8.0
    – spyrAlex
    Jan 14 at 9:55
  • reversed[i++] = bytes1(bytes32(48 + remainder));
    – Mad Jackal
    Jan 14 at 10:18
  • Hey @MadJackal I tried your suggestion and the error got removed! However after executing the code the end result of the function for any number is "string: \u0000" where the correct for a uint 1 should be "string: 1"
    – spyrAlex
    Jan 14 at 12:39
1

You cannot convert a uint256 to bytes1 directly, but if you convert it to uint8 first it works:

reversed[i++] = bytes1(uint8(48 + remainder));

So the full code looks like this:

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
  • It worked! Thanks for the suggestion.
    – spyrAlex
    Jan 14 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.