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?

Pabi
  • 1,129
  • 4
  • 11
  • 18

3 Answers3

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

Badr Bellaj
  • 18,780
  • 4
  • 58
  • 75
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);
      }
}
黃智祥
  • 465
  • 6
  • 16
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)

questionto42
  • 111
  • 5