Skip to main content

lib_jsl_information/source_coders/
gray_codes.rs

1//! Gray codes (reflected binary codes), in which consecutive values differ in exactly one bit.
2//!
3//! See the book entry [Entropy, divergence and mutual information](https://jwkunz.github.io/lib_jsl/book/information/entropy.html#gray-codes).
4
5/// Returns the reflected binary Gray code of `n`.
6// ANCHOR: gray
7pub fn gray_code(n: u64) -> u64 {
8    n ^ (n >> 1)
9}
10
11/// Inverts [`gray_code`]: returns the `n` whose Gray code is `g`.
12pub fn gray_decode(g: u64) -> u64 {
13    let mut n = g;
14    let mut shift = 1;
15    while shift < 64 {
16        n ^= n >> shift;
17        shift <<= 1;
18    }
19    n
20}
21// ANCHOR_END: gray
22
23/// Returns the full `bits`-bit Gray code sequence of length `2^bits` (`bits <= 32`).
24///
25/// # Panics
26/// Panics if `bits > 32`.
27pub fn gray_code_sequence(bits: u32) -> Vec<u64> {
28    assert!(bits <= 32, "gray_code_sequence supports at most 32 bits");
29    (0..1u64 << bits).map(gray_code).collect()
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn first_values() {
38        let seq: Vec<u64> = (0..8).map(gray_code).collect();
39        assert_eq!(seq, vec![0, 1, 3, 2, 6, 7, 5, 4]);
40    }
41
42    #[test]
43    fn round_trip() {
44        for n in (0..5000u64).chain([u64::MAX, u64::MAX / 3, 1 << 63]) {
45            assert_eq!(gray_decode(gray_code(n)), n);
46        }
47    }
48
49    #[test]
50    fn adjacent_codes_differ_by_one_bit() {
51        let seq = gray_code_sequence(10);
52        assert_eq!(seq.len(), 1024);
53        for w in seq.windows(2) {
54            assert_eq!((w[0] ^ w[1]).count_ones(), 1);
55        }
56        // The sequence is cyclic and a permutation.
57        assert_eq!((seq[0] ^ seq[1023]).count_ones(), 1);
58        let mut sorted = seq.clone();
59        sorted.sort();
60        assert!(sorted.iter().enumerate().all(|(i, &v)| v == i as u64));
61    }
62}