Extracting Bits From Bytes

Hello all, I decided to try learning Rust by building a diagnostics tool to decode a UDP control protocol I use at my day job. The UDP datagrams are fixed length, and have a fixed structure. Bytes 8 to 24 of the datagrams are used to represent 128 boolean states. So far I have figured out how to print the bytes as binary using the following code:

                let mut i = 0;
                let mut m = 8;
                for x in filled_buf[8..24].iter(){
                    let y = format!("{x:b}");
                    println!("GPO {}-{} is {}",i,m,y);
                    i = i + 8;
                    m = m + 8;
                }

This works, but I'd like a way to say "GPO {number} is {value}" instead of having to print an entire byte at a time. What would be the best way to achieve this?

Thanks all!

You can extract bits from a byte using shifting and bitwise operations. E. g. something like this works, though thereʼs probably multiple ways to achieve the same thing (and Iʼm not claiming that this one would have to be “the best” in any way):

fn main() {
    let x = 0b_01101010_u8;
    // check all the bits from LSB to MSB
    for i in 0..8 {
        let mask = 1 << i;
        let bit_is_set = (mask & x) > 0;
        println!("bit number {i} is set: {bit_is_set}");
    }
}

Rust Playground

bit number 0 is set: false
bit number 1 is set: true
bit number 2 is set: false
bit number 3 is set: true
bit number 4 is set: false
bit number 5 is set: true
bit number 6 is set: true
bit number 7 is set: false
1 Like

Speaking of alternative ways, instead of (1 << i) & x, one could work with (x >> i) & 1, too, which would more directly give a 0-or-1 value (of type u8), too, in case you need that.

That's perfect, thank you so much!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.