Convert bytes32 to string in Solidity

solidity convert bytes32 to string

In solidity, you must have wondered which one will make my code more efficient and my smart contracts better – Is it bytes32 or string? Today we will learn how to convert a bytes32 to string in Solidity.

Introduction

bytes32 and string are two different data types used in solidity. bytes32 is considered better than string by most of the solidity coders. What is the reason? It is not too complicated. Most programmers who uses solidity prefers bytes32 as compared to string because it has a better memory management.

Bytes32 VS string

As it is mentioned in the solidity docs:

As a general rule, use bytes for arbitrary-length raw byte data and string for arbitrary-length string (UTF-8) data. If you can limit the length to a certain number of bytes, always use one of the value types bytes1 to bytes32 because they are much cheaper.

https://docs.soliditylang.org/en/v0.8.15/types.html#bytes-and-string-as-arrays

So if you know or can limit the length of the string to a certain number than you can use one of the bytes1 to bytes32 whichever suits you the best. In addition to consuming lesser memory it will also consume less gas as compared to string.

Solution

Here is the code for conversion of bytes32 to string:

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);
    }

Code Explanation

First you declare a simple integer i which will be used to find the length of the bytes between 1-32. Then you run a while loop till i is less than 32. Also the value present in the bytes32 is not equal to 0. Meaning end of the value present in the bytes32 variable. After that we simply run a loop till length of the string and push each value one by one into the string variable.

      Best article on Converting bytes32 to String in Solidity ♥♥

Click here to Tweet this

Conclusion

You should not get into the bytes32 vs string debate that which one is better and which one is worse. Just look at the problem you are solving and use whatever suits you best.