How to update bitfields in rust?

What is the correct way to update bit fields in rust?
The update_sub1 function should update the sub1 bitfield with the u value.
I read rust don't have C like bitfields in struct.

fn update_sub1 (v: u32, u: u8) -> u32 {
        /* Need to update sub1 bits [26:23] alone with u value */
        **.. code here to update the 26:23 bits with u value ..** 
        return v;
}
fn main()
{
        /*  x: [31- status, 26:23 - sub1, 7:0 - sub2 ] */
        let x: u32 = 0x21;
        let y = update_sub1(x, 12);
        println!("{}", y);
}

You can just use bitwise operations, that's the standard procedure in any other language as well.

1 Like

If bitwise operations feel too error-prone, there's the bitvec crate that allows you to define your fields as actual bits, not as primitive integers, and work on them directly.

It has all the operations you need, including the ability to convert from bit slices to integer types via the BitField trait.

1 Like

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.