3

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!

2 Answers 2

6

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.

0

to convert from bytes to string simply do the following:

bytes data = 0xa22cb465;
string test = string(data);

The value 0xa22cb465 is not a UTF-8 character, so you'll get an error when attempting to convert it to string. Use the simple code below for testing.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

contract typeCasting{

    // hi = 0x6869;

    function bytesToString(bytes memory _data) public pure returns (string memory) {
        string memory result = string(_data);
        return result;
    }
}

all the best!

Your Answer

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

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