Skip to content

Commit

Permalink
Merge pull request #18 from dovgopoly/fix/add-bitlen
Browse files Browse the repository at this point in the history
fixed bitlen calc
  • Loading branch information
riordant authored Oct 9, 2024
2 parents f382bcf + a7d8d31 commit c77ffd7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/BigNumbers.sol
Original file line number Diff line number Diff line change
Expand Up @@ -997,8 +997,8 @@ library BigNumbers {
// with addition, if we assume that some a is at least equal to some b, then the resulting bit length will
// be a's bit length or (a's bit length)+1, depending on carry bit.this is cheaper than calling bitLength.
let msword := mload(add(result,0x20)) // get most significant word of result
// if(msword==1 || msword>>(max_bitlen % 256)==1):
if or( eq(msword, 1), eq(shr(mod(max_bitlen,256),msword),1) ) {
// if(carry==1 || msword>>(max_bitlen % 256)==1):
if or( eq(carry, 1), eq(shr(mod(max_bitlen,256),msword),1) ) {
max_bitlen := add(max_bitlen, 1) // if msword's bit length is 1 greater
// than max_bitlen, OR overflow occured,
// new bitlen is max_bitlen+1.
Expand Down
29 changes: 29 additions & 0 deletions test/BigNumbers.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,35 @@ contract BigNumbersTest is Test {
assertEq(BigNumbers.bitLength(1 << 255), 256);
}

function testAdd() public {
BigNumber memory lhs = hex"010000000000000000000000000000000000000000000000000000000000000001".init(false);
BigNumber memory rhs = hex"01".init(false);

BigNumber memory r = lhs.add(rhs);

assertEq(r.val, hex"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002");
assertEq(r.bitlen, 257);
assertEq(r.neg, false);

lhs = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".init(false);
rhs = hex"01".init(false);

r = lhs.add(rhs);

assertEq(r.val, hex"00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000");
assertEq(r.bitlen, 257);
assertEq(r.neg, false);

lhs = hex"0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".init(false);
rhs = hex"01".init(false);

r = lhs.add(rhs);

assertEq(r.val, hex"00000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000");
assertEq(r.bitlen, 261);
assertEq(r.neg, false);
}

function testShiftRight() public {
// shift by value greater than word length
BigNumber memory r;
Expand Down

0 comments on commit c77ffd7

Please sign in to comment.