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

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