#254 Jul 12, 2026

254. isolate_lowest_one — The x & x.wrapping_neg() Hack Finally Has a Name

Every bitmask codebase has an unexplained x & x.wrapping_neg() in it somewhere. Rust 1.97 gives the trick a name — and a sibling for the other end.

The folklore version

To keep only the lowest set bit of an integer, the two’s-complement trick is to AND the value with its own negation:

1
2
3
4
let x = 0b0101_0100_u8;

// lowest set bit, the folklore way
assert_eq!(x & x.wrapping_neg(), 0b0000_0100);

It works, it compiles to one instruction (BLSI on x86) — and it explains nothing to the next reader. For the highest set bit there isn’t even a one-liner: you shift 1 by leading_zeros arithmetic and special-case zero.

Named, on every integer type

Rust 1.97 stabilizes isolate_lowest_one and isolate_highest_one. They return the isolated bit as a mask — the value with all other bits cleared:

1
2
3
4
5
6
7
8
let x = 0b0101_0100_u8;

assert_eq!(x.isolate_lowest_one(),  0b0000_0100);
assert_eq!(x.isolate_highest_one(), 0b0100_0000);

// zero just stays zero — no panic, no sentinel
assert_eq!(0_u8.isolate_lowest_one(),  0);
assert_eq!(0_u8.isolate_highest_one(), 0);

Where bite 250’s lowest_one / highest_one answer “at which position?” (as an Option), the isolate_ pair answers “which bit?” — same information, shaped for masking instead of indexing.

The pattern: walk the set bits

The mask shape is exactly what you want for iterating over flags — grab the lowest bit, handle it, XOR it away:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let mut mask = 0b0101_0100_u8;
let mut seen = vec![];

while mask != 0 {
    let bit = mask.isolate_lowest_one();
    seen.push(bit);   // handle one flag
    mask ^= bit;      // clear it
}

assert_eq!(seen, [0b0000_0100,
                  0b0001_0000,
                  0b0100_0000]);

No positions, no shifting back and forth — each iteration hands you a ready-to-use single-bit mask. Signed types work too ((-8_i8).isolate_lowest_one() == 8), since the methods operate on the raw bit pattern.

If your code review comments still include “this ANDs x with its negation to isolate the lowest set bit…”, Rust 1.97 lets the method name say it for you.

← Previous 253. overflowing_add — Wrap, But Know It Happened