I want to convert a bytes of length, say n, to a string in Solidity.

bytes memory ret = new bytes(3);
ret[0] = 0x41; // A
ret[1] = 0x42; // B
ret[2] = 0x43; // C
return string(ret); // results in ""

Doesn't work.

I get the empty string as result.

Any suggestions?

  • Try this ret[0]= byte(A); ret[1]= byte(B); ret[2]= byte(C); – Afzaal Ahmad Oct 26 '17 at 12:04
  • Do you want to use char values for that? or can use just A, B, C? – Achala Dissanayake Oct 26 '17 at 14:10

This seems to be the go to code around here:

function bytes32ToString(bytes32 x) public returns (string) {
    bytes memory bytesString = new bytes(32);
    uint charCount = 0;
    for (uint j = 0; j < 32; j++) {
        byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
        if (char != 0) {
            bytesString[charCount] = char;
    bytes memory bytesStringTrimmed = new bytes(charCount);
    for (j = 0; j < charCount; j++) {
        bytesStringTrimmed[j] = bytesString[j];
    return string(bytesStringTrimmed);

I'm sure you can change out those 32's to get the length needed. But hope it helps!

  • What exactly does the function do? – Shuzheng Oct 26 '17 at 13:04
  • 1
    So as far as I understand, the EVM doesn't store strings, it stores things as bytes. So you can't store a string, you can just store bytes, which requires you to convert it if you want to do anything with it in Solidity. You've probably seen a lot of other posts to change string to bytes and that's in order to store the string in a way that you can call this function to get it back to a string. – thefett Oct 26 '17 at 15:18
  • Can I run this in Python? I don't know how to convert this into Python. Please help! Thanks – Russo May 22 '18 at 6:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.