Skip to content

Commit

Permalink
5.9 Right Shift Reverts on Bit Length Input
Browse files Browse the repository at this point in the history
  • Loading branch information
fmkra committed Oct 26, 2023
1 parent 0eafd0c commit 1cfbefb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/utils/bitwise.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,26 @@ fn left_shift<
fn right_shift<
T,
impl TZeroable: Zeroable<T>,
impl TOneable: Oneable<T>,
impl TAdd: Add<T>,
impl TSub: Sub<T>,
impl TMul: Mul<T>,
impl TDiv: Div<T>,
impl TOneable: Oneable<T>,
impl TCopy: Copy<T>,
impl TDrop: Drop<T>
>(
num: T, shift: T
) -> T {
let mut num = num;
let mut shift = shift;
let two = TOneable::one() + TOneable::one();
num / pow(two, shift)

loop {
if shift.is_zero() {
break num;
}
num = num / two;
shift = shift - TOneable::one();
}
}

// @notice Bit length of a number
Expand Down
1 change: 1 addition & 0 deletions src/utils/tests/test_bitwise.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ fn test_right_shift() {
assert(right_shift(256_u32, 8_u32) == 1, '256 >> 8');
assert(right_shift(512_u32, 8_u32) == 2, '512 >> 8');
assert(right_shift(65280_u32, 8_u32) == 255, '65280 >> 8');
assert(right_shift(128392_u32, 33_u32) == 0, '128392 >> 33');
}

#[test]
Expand Down

0 comments on commit 1cfbefb

Please sign in to comment.