0

How to go about converting a bytes32 variable to an uint256 variable in solidity? A straight forward conversion is not possible since when I converted the bytes32 variable which has a value of 99 to uint256.

uint256(0x3939000000000000000000000000000000000000000000000000000000000000)

I get the result

25882542651938552044065725088383013338356811605330942117523409242735587098624

1
  • Do you want to support only strings which represent decimal numbers? Nov 30 '20 at 9:41
2

First of all, note that 0x393900...00 represents 99 followed by 30 zeros.

In order to represent 99, you need to use 0x00...003939, or simply 0x3939.

If you do insist on supporting it in the other direction (because this is indeed how bytes32 stores ASCII strings), then note that 0x393800...00, for example, will be converted to 89 instead of 98.

In order to do it this way, replace i * 8 with 248 - i * 8 in the code below.


In order to handle decimal strings, you can use this:

function asciiToInteger(bytes32 x) public pure returns (uint256) {
    uint256 y;
    for (uint256 i = 0; i < 32; i++) {
        uint256 c = (uint256(x) >> (i * 8)) & 0xff;
        if (48 <= c && c <= 57)
            y += (c - 48) * 10 ** i;
        else
            break;
    }
    return y;
}

In order to handle also hexadecimal strings, you can add this:

        else if (65 <= c && c <= 90)
            y += (c - 65 + 10) * 10 ** i;
        else if (97 <= c && c <= 122)
            y += (c - 97 + 10) * 10 ** i;

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.