Solidity Error – Fixing Expected Primary Expression Error in Solidity ^0.8.0

solidity

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;
}

Best Answer

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;
}
Related Topic