deflate/
bit_reverse.rs

1/// Reverse the first length bits of n.
2/// (Passing more than 16 as length will produce garbage.
3pub fn reverse_bits(mut n: u16, length: u8) -> u16 {
4    debug_assert!(length <= 16);
5    // Borrowed from http://aggregate.org/MAGIC/#Bit%20Reversal
6    n = ((n & 0xaaaa) >> 1) | ((n & 0x5555) << 1);
7    n = ((n & 0xcccc) >> 2) | ((n & 0x3333) << 2);
8    n = ((n & 0xf0f0) >> 4) | ((n & 0x0f0f) << 4);
9    n = ((n & 0xff00) >> 8) | ((n & 0x00ff) << 8);
10    n >> (16 - length)
11}
12
13#[cfg(test)]
14mod test {
15    use super::reverse_bits;
16    #[test]
17    fn test_bit_reverse() {
18        assert_eq!(reverse_bits(0b0111_0100, 8), 0b0010_1110);
19        assert_eq!(
20            reverse_bits(0b1100_1100_1100_1100, 16),
21            0b0011_0011_0011_0011
22        );
23        // Check that we ignore >16 length
24        // We no longer check for this.
25        // assert_eq!(reverse_bits(0b11001100_11001100, 32), 0b0011001100110011);
26    }
27}