nickgammon / BigNumber

BigNumber library for the Arduino
MIT License
85 stars 22 forks source link

cast of negative number #6

Closed akita11 closed 6 years ago

akita11 commented 6 years ago

I've encountered a strange phenomena for casting negative numbers long-type valuables:

  long a = -33224;
  Serial.println(a);
  Serial.println((BigNumber)a);

This code results in:

-33224
32312

The second result of casted BigNumber seems to be the 2's complement of the original value in 16bit width. The similar casting for int-type value results the correct value.

nickgammon commented 6 years ago

There is no function bc_long2num however there is a bc_int2num in the underlying library. Thus there is a constructor for a BigNumber that takes an int but not one for a long. The problem isn't the casting, this is where it fails:

 BigNumber a = -33224;
 Serial.println(a);

The variable a is already wrong after the first line, so trying to cast it later doesn't change that. The simplest way to fix this is to construct from an appropriate string, eg.

  BigNumber a = "-33224";
  Serial.println(a);

Or, if you have an actual long that you want to use, then use sprintf to convert it to a string, and then use that string to form a BigNumber.

akita11 commented 6 years ago

Thanks, I understand. I'll close this issue.