I need to create function to convert byte3 to string. On my contract, data saved into state variable. now I want to convert content of variable for user. and this is my function :
function convertByteToString() public view returns(string memory){
string memory result = string(symbol);
return result;
}
but compiler error :
TypeError: Explicit type conversion not allowed from "bytes3" to "string memory".
how to fix error?Thanks in advance
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;
}
}