You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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);
}
}
The text was updated successfully, but these errors were encountered:
Should verify hex characters and implement proper error checking. Should look like:
}
The text was updated successfully, but these errors were encountered: