0

I am trying to use the uintToString method to convert a uint to string but I keep getting a weird square character in front of the resulting string.

How do I remove this character, or better yet how do I prevent it from appearing in the first place?

function uintToString(uint v) constant returns (string str) {
    uint maxlength = 100;
    bytes memory reversed = new bytes(maxlength);
    uint i = 0;
    while (v != 0) {
        uint remainder = v % 10;
        v = v / 10;
        reversed[i++] = byte(48 + remainder);
    }
    bytes memory s = new bytes(i + 1);
    for (uint j = 0; j <= i; j++) {
        s[j] = reversed[i - j];
    }
    str = string(s);
}
Shane Fontaine
  • 18,036
  • 20
  • 54
  • 82
Dino Anastos
  • 847
  • 1
  • 13
  • 22

1 Answers1

2

You have a bug in your reverse part. After while has finished, the value of i is the length of the array and not the index of the last element.

function uintToString(uint v) constant returns (string str) {
    uint maxlength = 100;
    bytes memory reversed = new bytes(maxlength);
    uint i = 0;
    while (v != 0) {
        uint remainder = v % 10;
        v = v / 10;
        reversed[i++] = byte(48 + remainder);
    }
    bytes memory s = new bytes(i);
    for (uint j = 0; j < i; j++) {
        s[j] = reversed[i - j - 1];
    }
    str = string(s);
}
ivicaa
  • 7,519
  • 1
  • 20
  • 50