Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to convert bitvec to slice? #243

Open
David-OConnor opened this issue Sep 4, 2023 · 1 comment
Open

How to convert bitvec to slice? #243

David-OConnor opened this issue Sep 4, 2023 · 1 comment

Comments

@David-OConnor
Copy link

David-OConnor commented Sep 4, 2023

Hi! I'm attempting to shift a &[u8] by 4 bits, using the bitvec crate.

Here's my naive guess from the Readme:

let bits  = (data.view_bits::<Msb0>()[4..]).as_raw_slice();

error:

51 |     let bits  = (data.view_bits::<Msb0>()[4..]).as_raw_slice()[..];
   |                                                  ^^^^^^^^^^^^ method cannot be called on `BitSlice<u8, Msb0>` due to unsatisfied trait bounds
   |
  ::: C:\Users\david\.cargo\registry\src\index.crates.io-6f17d22bba15001f\bitvec-1.0.1\src\slice.rs:60:1
   |
60 | pub struct BitSlice<T = usize, O = Lsb0>
   | ----------------------------------------
   | |
   | doesn't satisfy `BitSlice<u8, bitvec::order::Msb0>: BitViewSized`
   | doesn't satisfy `BitSlice<u8, bitvec::order::Msb0>: Sized`
   | doesn't satisfy `_: BitStore`

How would I do this? Thank you! I need to then pass this to a function as a byte array. I've found a workaround, but it's messy:

    let bits  = &data.view_bits::<Msb0>()[4..];

    let mut bit_i = 0;
    for _ in 0..num_commands {
        let byte0 = bits[bit_i..bit_i + 8].load_be();
        let byte1 = bits[bit_i+ 8..bit_i + 16].load_be();
        let byte2 = bits[bit_i + 16..bit_i + 24].load_be();
        let byte3 = bits[bit_i + 14..bit_i + 32].load_be();
        let command = ActuatorCommand::from_buf(&[byte0, byte1, byte2, byte3]);
        
        bit_i += COMMAND_SIZE * 8;
@connorskees
Copy link
Contributor

In your particular case, you could just load a u32 and call u32::to_be_bytes(). Otherwise, there's also BitVec::as_raw_slice. I don't see an equivalent method on BitSlice, however.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants