3

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?

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

3 Answers 3

2

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

3
  • 1
    Still get the same error
    – Pabi
    Commented Dec 20, 2016 at 21:14
  • 1
    @Pabi what error ? Commented Dec 20, 2016 at 21:32
  • 1
    it works for me perfectly check the pic in the answer. you resolve the error using memory keyword
    – Badr Bellaj
    Commented Dec 20, 2016 at 22:01
1

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

There is an import of a library that makes it possible with a int-to-string function, taken from How to convert uint to string in solidity?.

solidity ^0.8.0

import "@openzeppelin/contracts/utils/Strings.sol";

Strings.toString(myUINT)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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