Browse Source

CBigNum: Convert negative int64 values in a more well-defined way

Since the minimum signed integer cannot be represented as positive so long as its type is signed, and it's not well-defined what happens if you make it unsigned before negating it, we instead increment the negative integer by 1, convert it, then increment the (now positive) unsigned integer by 1 to compensate
0.8
Luke Dashjr 13 years ago
parent
commit
0f5a2a82d9
  1. 12
      src/bignum.h

12
src/bignum.h

@ -131,15 +131,9 @@ public:
if (sn < (int64)0) if (sn < (int64)0)
{ {
// We negate in 2 steps to avoid signed subtraction overflow, // Since the minimum signed integer cannot be represented as positive so long as its type is signed, and it's not well-defined what happens if you make it unsigned before negating it, we instead increment the negative integer by 1, convert it, then increment the (now positive) unsigned integer by 1 to compensate
// i.e. -(-2^63), which is an undefined operation and causes SIGILL n = -(sn + 1);
// when compiled with -ftrapv. ++n;
//
// Note that uint64_t n = sn, when sn is an int64_t, is a
// well-defined operation and n will be equal to sn + 2^64 when sn
// is negative.
n = sn;
n = -n;
fNegative = true; fNegative = true;
} else { } else {
n = sn; n = sn;

Loading…
Cancel
Save