Changing or re-interpreting the order of bitvec / bitslice

Hi,

I'm using bitvec to encode six-bit AIS code. How can I change or re-interpret the ordering of a bitvec or bitslice:

        let tb = bits![u8, Msb0; 0, 0, 0, 0, 0, 0, 1, 0];
        assert_eq!(2u8, tb.load::<u8>());

        let tb = bits![u8, Lsb0; 0, 0, 0, 0, 0, 0, 1, 0];
        assert_eq!(2u8, tb.load::<u8>()); // fails (as expected). How can I convert tb to Msb0 first?

Thanks, Gaute

You could reverse tb:

let tb = bits![mut u8, Lsb0; 0, 0, 0, 0, 0, 0, 1, 0];
tb.reverse();
assert_eq!(2u8, tb.load::<u8>());

Rustexplorer.

2 Likes

Thanks. That's possible. Shouldn't it be possible to change the interpretation though? Or is that already tied to how the data is stored?

Another question, why aren't these equal, and how do I make them equal..:

        let b = bits![u8, Msb0;
            0, 0, 0, 0, 1, 0,
            0, 0, 0, 0, 1, 0];

        println!("{:?}", &b[..6]);
        println!("{:?}", &b[6..]);

        let a = b[..6].load::<u8>();
        let b = b[6..].load::<u8>();

        assert_eq!(a,b);

Output:

BitSlice<u8, bitvec::order::Msb0> { addr: 0x7f9d307fe45c, head: 000, bits: 6 } [0, 0, 0, 0, 1, 0]
BitSlice<u8, bitvec::order::Msb0> { addr: 0x7f9d307fe45c, head: 110, bits: 6 } [0, 0, 0, 0, 1, 0]
thread 'sixbit::tests::test_offset' panicked at src/sixbit.rs:130:9:
assertion failed: `(left == right)`
  left: `2`,
 right: `8`

If force_align a bitvec before loading, it loads correctly.

Yes, the layout of the underlying buffer changes based on msb and lsb, not just how the bits are interpreted.

I think this is happening, because you are loading a big endian bitvec on a little endian machine. I.e. if you replace load::<u8>() with load_be::<u8>(), it works. As to why that is I'm not exactly sure, but the documentation of load states:

You must always use the loading method that exactly corresponds to the storing method previously used to insert data into the bit-slice: same suffix on the method name (none, _le, _be) and same integer type. bitvec is not required to, and will not, guarantee round-trip consistency if you change any of these parameters.

1 Like

Yeah, that seems to work too! Puh.. not sure if this crate is helping me out or making things more complicated.

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.