For example if I have a bytes4 variable that is "0xabcd1122" is there any way to turn this into a string with a value of "abcd1122"? I am asking because I want to assign a unique identifier to a token symbol but when I convert bytes to a string the result does not fit utf-8 encoding making the output garbled. If converting the characters that make up the bytes variable into a string doesn't work, does anybody have any idea to generate a unique identifier as a string?
1 Answer
Here's a function to do it:
function getHexString(bytes4 value) pure public returns (string) {
bytes memory result = new bytes(8);
string memory characterString = "0123456789abcdef";
bytes memory characters = bytes(characterString);
for (uint8 i = 0; i < 4; i++) {
result[i * 2] = characters[uint256((value[i] & 0xF0) >> 4)];
result[i * 2 + 1] = characters[uint256(value[i] & 0xF)];
}
return string(result);
}
You can try it here: https://ethfiddle.com/726_Ju8bse.