0

I have this function that converts a unit to a hex string:

function uintToHexString(uint i) public pure returns (string memory) {
    if (i == 0) return "0";
    uint j = i;
    uint length;
    while (j != 0) {
        length++;
        j = j >> 4;
    }
    uint mask = 15;
    bytes memory bstr = new bytes(length);
    uint k = length;
    while (i != 0) {
        uint curr = (i & mask);
        bstr[--k] = curr > 9 ?
            bytes1(uint8(55 + curr)) :
            bytes1(uint8(48 + curr)); // 55 = 65 - 10
        i = i >> 4;
    }
    return string(bstr);
}

The above function works as intended. For example, when I pass in the number 255 it returns the string "FF".

Now, I am having trouble creating a function that does the reverse- takes the string "FF" (or any hex string in general) and returns the corresponding uint value.

1 Answer 1

0

Try this... Can probably be optimized for gas consumption but will get the job done.

pragma solidity 0.8.13;

contract ConvertStuff {

    function numberFromAscII(bytes1 b) private pure returns (uint8 res) {
        if (b>="0" && b<="9") {
            return uint8(b) - uint8(bytes1("0"));
        } else if (b>="A" && b<="F") {
            return 10 + uint8(b) - uint8(bytes1("A"));
        } else if (b>="a" && b<="f") {
            return 10 + uint8(b) - uint8(bytes1("a"));
        }
        return uint8(b); // or return error ... 
    }

   

    function convertString(string memory str) public pure returns (uint256 value) {
        
        bytes memory b = bytes(str);
        uint256 number = 0;
        for(uint i=0;i<b.length;i++){
            number = number << 4; // or number = number * 16 
            number |= numberFromAscII(b[i]); // or number += numberFromAscII(b[i]);
        }
        return number; 
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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