bit_utils.rs 1008 Bytes
Newer Older
1 2
// u8

qinsoon's avatar
qinsoon committed
3
#[inline(always)]
qinsoon's avatar
qinsoon committed
4 5
pub fn test_nth_bit_u8(value: u8, index: usize, val: u8) -> bool {
    ((value >> index) & 1) as u8 == val
qinsoon's avatar
qinsoon committed
6 7 8
}

#[inline(always)]
9
pub fn lower_bits_u8(value: u8, len: usize) -> u8 {
qinsoon's avatar
qinsoon committed
10 11 12
    value & ((1 << len) - 1)
}

13 14 15 16 17 18 19 20
// u64

#[inline(always)]
pub fn set_nth_bit_u64 (value: u64, index: usize, set_value: u8) -> u64 {
    value ^ (((-(set_value as i64) as u64) ^ value) & (1 << index))
}

#[inline(always)]
qinsoon's avatar
qinsoon committed
21 22
pub fn test_nth_bit_u64(value: u64, index: usize, val: u8) -> bool {
    ((value >> index) & 1) as u8 == val
23 24
}

qinsoon's avatar
qinsoon committed
25 26 27 28 29 30 31 32
#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    pub fn test_u8_bits() {
        let value : u8 = 0b1100_0011;
        
33
        assert_eq!(test_nth_bit_u8(value, 6), true);
qinsoon's avatar
qinsoon committed
34
        
35 36 37 38 39 40 41 42 43 44
        assert_eq!(lower_bits_u8(value, 6), 0b00_0011);
    }

    #[test]
    pub fn test_set_bit() {
        let a = 0b0000u64;
        let b = 0b1111u64;

        assert_eq!(set_nth_bit_u64(a, 2, 1), 0b100);
        assert_eq!(set_nth_bit_u64(b, 2, 0), 0b1011);
qinsoon's avatar
qinsoon committed
45
    }
46
}