File: bits_position.rs

package info (click to toggle)
rust-bitfield 0.17.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 196 kB
  • sloc: makefile: 4
file content (75 lines) | stat: -rw-r--r-- 1,835 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#[macro_use]
extern crate bitfield;

use bitfield::BitMut;
use bitfield::BitRangeMut;

bitfield! {
    struct BitsLocations([u8]);
}

bitfield! {
    struct BitsLocationsMsb0(MSB0 [u8]);
}

fn println_slice_bits(slice: &[u8]) {
    if slice.is_empty() {
        println!("[]");
    } else {
        print!("[{:08b}", slice[0]);

        for byte in &slice[1..] {
            print!(", {:08b}", byte);
        }

        println!("]");
    }
}

fn main() {
    let mut bits_locations = BitsLocations([0; 3]);
    let mut bits_locations_msb0 = BitsLocationsMsb0([0; 3]);

    println!("Default version:");
    for i in 0..(3 * 8) {
        bits_locations.set_bit(i, true);
        print!("{:2}: ", i);
        println_slice_bits(&bits_locations.0);
        bits_locations.set_bit(i, false);
    }

    for i in 0..(3 * 8 - 3) {
        let msb = i + 3;
        let lsb = i;
        for value in &[0b1111u8, 0b0001, 0b1000] {
            bits_locations.set_bit_range(msb, lsb, *value);
            print!("{:2} - {:2} ({:04b}): ", msb, lsb, value);
            println_slice_bits(&bits_locations.0);
        }
        println!();
        bits_locations.set_bit_range(msb, lsb, 0u8);
    }

    println!("MSB0 version:");

    for i in 0..(3 * 8) {
        bits_locations_msb0.set_bit(i, true);
        print!("{:2}: ", i);
        println_slice_bits(&bits_locations_msb0.0);

        bits_locations_msb0.set_bit(i, false);
    }

    for i in 0..(3 * 8 - 3) {
        let msb = i + 3;
        let lsb = i;
        for value in &[0b1111u8, 0b0001, 0b1000] {
            bits_locations_msb0.set_bit_range(msb, lsb, *value);
            print!("{:2} - {:2} ({:04b}): ", msb, lsb, value);
            println_slice_bits(&bits_locations_msb0.0);
        }
        println!();

        bits_locations_msb0.set_bit_range(msb, lsb, 0u8);
    }
}