1

This may be simple in other languages but I can't figure out how to do it in Solidity. I have a bytes32 like this 0x05416460deb76d57af601be17e777b93592d8d4d4a4096c57876a91c84f4a712.

I don't want to convert the bytes to a string, rather I just want to represent the whole thing as a string, like "0x05416460deb76d57af601be17e777b93592d8d4d4a4096c57876a91c84f4a712". How can this be done in Solidity?

1 Answer 1

1

You have to individually get the bytes from bytes32. Each byte represents two numbers from hex value. You can individually map the numbers from hex value to corresponding char value in the ASCII table. An example implementation is demonstrated below.

function bytes32ToLiteralString(bytes32 data) 
    public
    pure
    returns (string memory result) 
{
    bytes memory temp = new bytes(65);
    uint256 count;

    for (uint256 i = 0; i < 32; i++) {
        bytes1 currentByte = bytes1(data << (i * 8));
        
        uint8 c1 = uint8(
            bytes1((currentByte << 4) >> 4)
        );
        
        uint8 c2 = uint8(
            bytes1((currentByte >> 4))
        );
    
        if (c2 >= 0 && c2 <= 9) temp[++count] = bytes1(c2 + 48);
        else temp[++count] = bytes1(c2 + 87);
        
        if (c1 >= 0 && c1 <= 9) temp[++count] = bytes1(c1 + 48);
        else temp[++count] = bytes1(c1 + 87);
    }
    
    result = string(temp);
}

For upper-case hex letters, use 55 instead of 87.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.