Solidity String Conversion – How to Convert a Bytes32 to String

bytes32soliditystring

How can I convert a bytes32 to a string? Does anyone has a magic function or library which does it?

Best Answer

Based on the latest compiler version 0.4.24, I use the following.

function convertingToString()public returns(string){
bytes32 memory hw = "Hello World";
string memory converted = string(hw);
return converted;
}

Using explicit conversion to carry it out. The reverse is also possible.

For versions 0.5.0+ please use (tested from 0.5 to 0.7.2 - it is likely that it will continue to work past 0.7.2):

function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
        uint8 i = 0;
        while(i < 32 && _bytes32[i] != 0) {
            i++;
        }
        bytes memory bytesArray = new bytes(i);
        for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
            bytesArray[i] = _bytes32[i];
        }
        return string(bytesArray);
    }
Related Topic