GitLab will be upgraded on 30 Jan 2023 from 2.00 pm (AEDT) to 3.00 pm (AEDT). During the update, GitLab and Mattermost services will not be available. If you have any concerns with this, please talk to us at N110 (b) CSIT building.

bit_utils.rs 1.92 KB
Newer Older
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Copyright 2017 The Australian National University
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
16
// u8

qinsoon's avatar
qinsoon committed
17
#[inline(always)]
qinsoon's avatar
qinsoon committed
18
19
pub fn test_nth_bit_u8(value: u8, index: usize, val: u8) -> bool {
    ((value >> index) & 1) as u8 == val
qinsoon's avatar
qinsoon committed
20
21
22
}

#[inline(always)]
23
pub fn lower_bits_u8(value: u8, len: usize) -> u8 {
qinsoon's avatar
qinsoon committed
24
25
26
    value & ((1 << len) - 1)
}

27
28
// u64

29
30
31
32
33
34
35
36
37
38
39
40
41
42
#[inline(always)]
// Returns the number that has 'n' 1's in a row (i.e. 2^n-1)
pub fn bits_ones(n: usize) -> u64 {
    if n == 64 { (-(1 as i64)) as u64 }
        else { (1 << n) - 1 }
}

#[inline(always)]
pub fn u64_asr(val: u64, shift: u32) -> u64 {
    let _val: i64 = val as i64;
    let res: i64 = _val >> shift;
    res as u64
}

43
44
45
46
47
48
#[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
49
50
pub fn test_nth_bit_u64(value: u64, index: usize, val: u8) -> bool {
    ((value >> index) & 1) as u8 == val
51
52
}

qinsoon's avatar
qinsoon committed
53
54
55
56
57
58
59
60
#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    pub fn test_u8_bits() {
        let value : u8 = 0b1100_0011;
        
61
        assert_eq!(test_nth_bit_u8(value, 6, 1), true);
qinsoon's avatar
qinsoon committed
62
        
63
64
65
66
67
68
69
70
71
72
        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
73
    }
74
}