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.
Code
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
}Report a problem with this exampleOpens a pre-filled issue on GitHub.