Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hex to address function is wrong #76

Open
dshiell opened this issue Apr 4, 2024 · 0 comments
Open

hex to address function is wrong #76

dshiell opened this issue Apr 4, 2024 · 0 comments
Assignees

Comments

@dshiell
Copy link
Collaborator

dshiell commented Apr 4, 2024

Should verify hex characters and implement proper error checking. Should look like:

* Converts a hexadecimal string to an address.
 * Assumes the hexadecimal string is prefixed with "0x".
 * @param _hexStr The hexadecimal string to convert.
 * @return addr The address converted from the hexadecimal string.
 */
function hexStrToAddress(string memory _hexStr) public pure returns (address addr) {
    bytes memory hexBytes = bytes(_hexStr);

    // Check if the string has an appropriate length: 2 characters for "0x" and 40 characters for the address
    require(hexBytes.length == 42, "Invalid length of the hexadecimal string.");

    uint160 total = 0;
    uint160 base = 1;
    for (uint256 i = hexBytes.length - 1; i >= 2; i--) {
        uint160 digit;
        // Convert ASCII to integer value
        if (uint8(hexBytes[i]) >= 48 && uint8(hexBytes[i]) <= 57) {
            // '0' to '9'
            digit = uint160(uint8(hexBytes[i]) - 48);
        } else if (uint8(hexBytes[i]) >= 65 && uint8(hexBytes[i]) <= 70) {
            // 'A' to 'F'
            digit = uint160(uint8(hexBytes[i]) - 55);
        } else if (uint8(hexBytes[i]) >= 97 && uint8(hexBytes[i]) <= 102) {
            // 'a' to 'f'
            digit = uint160(uint8(hexBytes[i]) - 87);
        } else {
            revert("Invalid character in the hexadecimal string.");
        }
        total += digit * base;
        base *= 16;
    }

    return address(total);
}

}

@RnkSngh RnkSngh self-assigned this Apr 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants