Bit Manipulation Gray Code Sequence (Rust)

Generate a Gray code sequence of n bits in Rust using bit manipulation where consecutive values differ by one bit.

RustData Integrity

Code

rustsnippet
11 lines
fn gray_code(n: u32) -> Vec<u32> {
    let count = 1u32 << n;
    (0..count).map(|i| i ^ (i >> 1)).collect()
}

fn popcount(mut x: u32) -> u32 {
    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0f0f0f0f;
    (x * 0x01010101) >> 24
}

How the snippet works

Bit Manipulation Gray Code Sequence (Rust) keeps everything in the functions gray_code and popcount.

Using it

The main signature reads fn gray_code(n: u32) -> Vec<u32>

The surface worth importing is gray_code; the helpers around it are private to the snippet.

Key statements

(0..count).map(|i| i ^ (i >> 1)).collect()
}
fn popcount(mut x: u32) -> u32 {
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0f0f0f0f;
(x * 0x01010101) >> 24
}

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `gray_code`, `popcount` at load time.