Solidity – How to Convert Bytes to Hexadecimal String

bytessoliditystring

In a smart contract I have stored a bytes4 value: 0xa22cb465. I'd like to parse this value as a string:

string memory test = "0xa22cb465"

I've only stumbled upon explanations on how to convert bytes to string, not parse. Thanks in advance for the help!

Best Answer

If I understand correctly by "parsing" you mean going from an integer representation (i.e., bytes4 data = 0xa22cb465;) to a string representation in hexadecimal (i.e., string memory test = "0xa22cb465").

In that case, you'd need to write a function to actually do that conversion. Here is an example working with bytes input and base 16 string output with "0x" prefix.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;

contract Example {
    bytes4 public data = 0xa22cb465;

    function howToUseIt() public view returns (string memory) {
        return iToHex(abi.encodePacked(data));
    }

    function iToHex(bytes memory buffer) public pure returns (string memory) {

        // Fixed buffer size for hexadecimal convertion
        bytes memory converted = new bytes(buffer.length * 2);

        bytes memory _base = "0123456789abcdef";

        for (uint256 i = 0; i < buffer.length; i++) {
            converted[i * 2] = _base[uint8(buffer[i]) / _base.length];
            converted[i * 2 + 1] = _base[uint8(buffer[i]) % _base.length];
        }

        return string(abi.encodePacked("0x", converted));
    }
}

I hope that answers your question.

Related Topic