Trying to convert address string to type address in Solidity

I am trying to convert address string to type address in solidity but when I am doing

 function StringToBytes(string memory _str) public pure returns (bytes memory) { return bytes(_str); } function StringToBytesLength(string memory _str) public pure returns (uint256) { return bytes(_str).length; }

The result of StringToBytes is giving me 42 which should ideally gives me 20. If I am trying the same thing in python i.e convert string to bytes , it is giving me 20 bytes which is the length of an ethereum address in bytes. I had found several solutions to convert address string to address type but none of them is working for solidity version 0.7. Please help.

1 Answer

I want a solution but it is not optimal, I am looking for a solution which is lighter on gas fees, It is now consuming 77492.

 function fromHexChar(uint8 c) public pure returns (uint8) { if (bytes1(c) >= bytes1('0') && bytes1(c) <= bytes1('9')) { return c - uint8(bytes1('0')); } if (bytes1(c) >= bytes1('a') && bytes1(c) <= bytes1('f')) { return 10 + c - uint8(bytes1('a')); } if (bytes1(c) >= bytes1('A') && bytes1(c) <= bytes1('F')) { return 10 + c - uint8(bytes1('A')); } return 0; } function hexStringToAddress(string calldata s) public pure returns (bytes memory) { bytes memory ss = bytes(s); require(ss.length%2 == 0); // length must be even bytes memory r = new bytes(); for (uint i=0; i< ++i) { r[i] = bytes1(fromHexChar(uint8(ss[2*i])) * 16 + fromHexChar(uint8(ss[2*i+1]))); } return r; } function toAddress(string calldata s) public pure returns (address) { bytes memory _bytes = hexStringToAddress(s); require(_bytes.length >= 1 + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), 1)), 0x1000000000000000000000000) } return tempAddress; }
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like