Skip to content

Instantly share code, notes, and snippets.

@tangert
Created November 23, 2021 20:56
Show Gist options
  • Save tangert/b6a84d52146298d756f5bcb8a1eaf497 to your computer and use it in GitHub Desktop.
Save tangert/b6a84d52146298d756f5bcb8a1eaf497 to your computer and use it in GitHub Desktop.
split a solidity address into its individual characters.
function getAddressChars(address _address)
private
pure
returns (bytes memory)
{
bytes memory hexSymbols = "0123456789abcdef";
uint256 value = uint256(uint160(_address));
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
uint256 bufferLength = 2 * length + 2;
bytes memory chars = new bytes(bufferLength);
// // first two chars will always be 0x.
chars[0] = "0";
chars[1] = "x";
// // first fill up the buffer
// start at 2 because we already know that the first two characters are 0x.
for (uint256 i = 2; i < bufferLength; i++) {
// for whatever reason, this fills up the buffer starting from the end
// so here we are incrementing up but filling in the end of the array first.
// if someone knows how to fix this
chars[bufferLength - i + 1] = hexSymbols[value & 0xf];
value >>= 4;
}
return chars;
}
/*
Usage:
bytes memory chars = getAddressChars(_address);
// now you can access each character of an address directly through an index.
// so string(char[0]) returns "0", string(char[1]) returns "x", etc.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment