Skip to content

Commit 910c13c

Browse files
committed
Fix undefined behaviour
Shifting negative signed integers is undefined behaviour, so use unsigned integers everywhere.
1 parent 02957fa commit 910c13c

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

include/int256_t.hpp

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,10 @@ class int256_t
5757

5858
bool operator<(const int256_t& other) const
5959
{
60-
return high < other.high ||
61-
(high == other.high && low < other.low);
60+
int128_t hi1 = high;
61+
int128_t hi2 = other.high;
62+
63+
return hi1 < hi2 || (hi1 == hi2 && low < other.low);
6264
}
6365

6466
bool operator<=(const int256_t& other) const
@@ -157,8 +159,8 @@ class int256_t
157159

158160
if (low <= max64 &&
159161
other.low <= max64 &&
160-
((high == 0 || high == -1) &&
161-
(other.high == 0 || other.high == -1)))
162+
((high == 0 || ~high == 0) &&
163+
(other.high == 0 || ~other.high == 0)))
162164
{
163165
return int256_t(low * other.low,
164166
(high == other.high) ? 0 : -1);
@@ -466,9 +468,9 @@ class int256_t
466468

467469
private:
468470
uint128_t low;
469-
int128_t high;
471+
uint128_t high;
470472

471-
int256_t(uint128_t low, int128_t high)
473+
int256_t(uint128_t low, uint128_t high)
472474
: low(low)
473475
, high(high)
474476
{

0 commit comments

Comments
 (0)