DEV Community

Mister Singh
Mister Singh

Posted on

let's convert between bytes32 & string & vice-versa


Before we talk about how to convert between bytes32 & string, let us first know the reason why we may want to do this.

So bytes32 has a fixed size and strings are dynamically sized. This produces some interesting cases like a contract can't return another contract a string or a contract can't call another contract with a string.

So a reasonable alternative is to use bytes32 instead of strings. This makes our code composable.

string -> bytes32

string memory input = "hicksville"
bytes32 output = bytes32(abi.encodePacked(input))
Enter fullscreen mode Exit fullscreen mode

string to bytes32

bytes32 -> string

string memory reversedInput = string(abi.encodePacked(output))
Enter fullscreen mode Exit fullscreen mode

bytes32 to string

Top comments (0)