Home > Software design >  Convert bytes3 to string in Solidity
Convert bytes3 to string in Solidity

Time:04-17

I need to create function to convert byte3 to string. On my contract, data is saved into a state variable.

I want to convert content of variable for user.

This is my function:

function convertByteToString() public view returns(string memory){
    string memory result = string(symbol);
    return result;
}

but I get a compiler error:

TypeError: Explicit type conversion not allowed from "bytes3" to "string memory".

How can this error be resolved?

CodePudding user response:

To convert bytes3 to string you must use the abi.encodePacked(bytes3 parameter) and this result you must convert it into a string.

Change your function with this:

function convertByteToString(bytes3 symbol) public view returns(string memory){
  string memory result = string(abi.encodePacked(symbol));
  return result;
}

CodePudding user response:

Only a dynamic-length byte array (Solidity type bytes) can be typecasted to a string, but you're passing a fixed-length byte array (Solidity type bytes3).

Use abi.encode() to convert the bytes3 to bytes.

pragma solidity ^0.8;

contract MyContract {
    bytes3 symbol = 0x455448; // hex-encoded ASCII value of "ETH"

    function convertByteToString() public view returns(string memory){
        string memory result = string(abi.encode(symbol));
        return result;
    }
}
  • Related