Skip to content

Commit

Permalink
Fix Bit_Length Will Revert if Input Most
Browse files Browse the repository at this point in the history
Significant Bit Is 1
  • Loading branch information
fmkra committed Oct 19, 2023
1 parent 5244956 commit 4a21a3c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/utils/bitwise.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -49,24 +49,25 @@ fn right_shift<
fn bit_length<
T,
impl TZeroable: Zeroable<T>,
impl TPartialOrd: PartialOrd<T>,
impl TAddImpl: Add<T>,
impl TSub: Sub<T>,
impl TMul: Mul<T>,
impl TOneable: Oneable<T>,
impl TPartialEq: PartialEq<T>,
impl TAddImpl: Add<T>,
impl TDiv: Div<T>,
impl TCopy: Copy<T>,
impl TDrop: Drop<T>
>(
num: T
) -> T {
let mut bit_position = TZeroable::zero();
let mut cur_n = TOneable::one();
let mut cur_n = num;
let two = TOneable::one() + TOneable::one();

loop {
if cur_n > num {
if cur_n == TZeroable::zero() {
break ();
};
bit_position = bit_position + TOneable::one();
cur_n = left_shift(cur_n, TOneable::one());
cur_n = cur_n / two;
};
bit_position
}
Expand Down
5 changes: 5 additions & 0 deletions src/utils/tests/test_bitwise.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,8 @@ fn test_bit_length() {
assert(bit_length(8_u32) == 4, 'bit length of 8 is 4');
}

#[test]
#[available_gas(999999999)]
fn test_bit_length_most_significant_bit_one() {
assert(bit_length(4294967295_u32) == 32, 'bit length of 2^32-1 is 32');
}

0 comments on commit 4a21a3c

Please sign in to comment.