1

How can I parse an integer (uint) to a string in solidity?

This is what I have attempted to do so far:

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

But the following line returns an error:

string myString= bytes32ToString(bytes32(myInteger));

Type string memory is not implicitly convertible to expected type string storage pointer.

Why is this?

  • 1
    Does this answer your question ? – Teleporting Goat Dec 20 '16 at 17:03
  • I am getting an error with that code. I have updated my question with the details. – Pabi Dec 20 '16 at 18:10
1

try this code :

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

    return string(bytesString);
  }

   function My_integ(bytes32 myInteger) returns (string){

        string memory myString= bytes32ToString( myInteger );
return myString;
   }   

enter image description here

  • Still get the same error – Pabi Dec 20 '16 at 21:14
  • @Pabi what error ? – Teleporting Goat Dec 20 '16 at 21:32
  • it works for me perfectly check the pic in the answer. you resolve the error using memory keyword – Badr Bellaj Dec 20 '16 at 22:01
0

Try this. It works.

pragma solidity ^0.4.2;
contract UintToStr {  
     function UintToString(uint v) constant returns (string) {
          bytes32 ret;
            if (v == 0) {
                 ret = '0';
            }
            else {
                 while (v > 0) {
                      ret = bytes32(uint(ret) / (2 ** 8));
                      ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
                      v /= 10;
                 }
            }

            bytes memory bytesString = new bytes(32);
            for (uint j=0; j<32; j++) {
                 byte char = byte(bytes32(uint(ret) * 2 ** (8 * j)));
                 if (char != 0) {
                      bytesString[j] = char;
                 }
            }

            return string(bytesString);
      }
}

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.