NumberToString::_itoa bug

  • johny7

    johny7 - 2011-09-16

    Please fix it, it doesn't work for negative number like 0x80000000. (Whlist long and int sizeof are same).

  • Jonathan Wallace

    A couple of things.  First, hexidecimal implies unsigned, always.  This is not a libjson standard, all programming languages share this.  That value represents 2147483648.

    cout << NumberToString::_itoa<unsigned long>(0x80000000) << endl;
    prints out 2147483648 as it should.

    cout << NumberToString::_itoa<int>(0x80000000) << endl;
    prints out -2147483648 because it overflowed into the negative.

    You should not represent negative values as hex because of the implied unsigned-ness.  This goes for everything, not just libjson.


  • johny7

    johny7 - 2011-09-20

    Sorry, but I was talking about exact function in Json library, which contains bug. Please look into it more carefully:

    template<typename T>
        static json_string _itoa(T val) json_nothrow {
       #ifdef JSON_LESS_MEMORY
      json_auto<json_char> s(getLenSize<sizeof(T)>::GETLEN);
      json_char num_str_result;
       num_str_result = JSON_TEXT('\0'); //null terminator
       json_char * runner = &num_str_result;
       bool negative;

       long value = (long)val;
       //first thing, check if it's negative, if so, make it positive
       if (value < 0){
      value = -value;
      negative = true;
       } else {
      negative = false;

       //create the string
       do {
      *runner- = (json_char)(value % 10) + JSON_TEXT('0');
       } while(value /= 10);

       //if it's negative, add the negation
       if (negative){
      *runner = JSON_TEXT('-');
      return json_string(runner);
       return json_string(runner + 1);

    It doesn't work for integers in the form of 0x800000… (which for 32 bit windows is -2147483648), and when sizeof(long) = sizeof(int) (so, on the majority of the platforms).

    I'm not already mention that if you'll define JSON_LESS_MEMORY, it simply won't compile.


Log in to post a comment.