Solidity – Issue in Explicit Type Conversion from uint256 to bytes1

design-patternsremixsolidity

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

Best Answer

Change your error statement to this :

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

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

Related Topic