Skip to content

Commit e8a1abd

Browse files
committed
Add clearLowestSetBit (blsr)
1 parent c1e74d5 commit e8a1abd

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

bithacks.zig

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1700,3 +1700,16 @@ test "Compute the lexicographically next bit permutation" {
17001700
try expectEqual(nextLexicographicPermutation(@as(u32, 0b00011010)), 0b00011100);
17011701
try expectEqual(nextLexicographicPermutation(@as(u32, 0b00011100)), 0b00100011);
17021702
}
1703+
1704+
/// Clear the lowest set bit. The optimizer seems to correctly lower this to blsr and equivalent instructions.
1705+
/// (This is an addition to the original bithacks document)
1706+
pub fn clearLowestSetBit(val: anytype) @TypeOf(val) {
1707+
return val & (val - 1);
1708+
}
1709+
1710+
test "Clear least significant set bit " {
1711+
try expectEqual(clearLowestSetBit(@as(u32, 0b00000001)), 0b00000000);
1712+
try expectEqual(clearLowestSetBit(@as(u32, 0b00011010)), 0b00011000);
1713+
try expectEqual(clearLowestSetBit(@as(u64, 0b00000001)), 0b00000000);
1714+
try expectEqual(clearLowestSetBit(@as(u64, 0b000110110001101100011011000110110001101100011000)), 0b000110110001101100011011000110110001101100010000);
1715+
}

0 commit comments

Comments
 (0)