2

I am trying to convert the unit to string using the method. I have the "TypeError" in the line. Please check the screen shot below for the error message.

function uint2str(uint i) internal pure returns (string memory) {
    if (i == 0) return "0";
    uint j = i;
    uint length;
    while (j != 0) {
        length++;
        j /= 10;
    }
    bytes memory bstr = new bytes(length);
    uint k = length - 1;
    while (i != 0) {
        bstr[k--] = byte(48 + i % 10);   ----> this is the place I get error
        i /= 10;
    }
    return string(bstr);
}

enter image description here

5

Change your error statement to this :

bstr[k--] = byte(uint8(48 + i % 10)); 

It will work because of same bit length of both types.

3
  • But i is uint256 .. how I can convert it to uint8 .. there will be data loss
    – iappmaker
    Jan 31 '19 at 8:04
  • 1
    i%10 will be a single digit since 0 to 9 always. Adding it to 48 will be in the limit of uint8.
    – Aniket
    Jan 31 '19 at 8:11
  • Great.. I will try and update / accept
    – iappmaker
    Jan 31 '19 at 8:12

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.