bitvec icon indicating copy to clipboard operation
bitvec copied to clipboard

`to_bitvec` and related functions returning invalid values

Open XAMPPRocky opened this issue 2 years ago • 4 comments

Hello, if you run the below code you can see that while these should return the same value, the second instance returns [0x7, 0x80].

use bitvec::prelude::*;
assert_eq!(bitvec::bits![u8, Msb0;       0, 0, 0, 1, 1, 1, 0, 1].to_bitvec().into_vec(), vec![29]);
assert_eq!(bitvec::bits![u8, Msb0; 1, 1, 0, 0, 0, 1, 1, 1, 0, 1][2..].to_bitvec().into_vec(), vec![29]);

XAMPPRocky avatar May 29 '23 00:05 XAMPPRocky

Is this an endianess problem?

let data: Vec<u8> = vec![0b0000_0000, 0b1111_1111];
let slice = data.view_bits::<Msb0>();
info!("{:04b}", slice[6..10].load::<u64>());

is printing 1100 instead of 0011.

I work around this with a loop (read until word boundary, shift subslice to the left, continue), but that means I have to do sign extension manually.

Bug or a feature?

Trolldemorted avatar Mar 05 '24 23:03 Trolldemorted

Ran your numbers, in your case it does not look like an endianess problem, and rather like a generic "reads across word boundaries" problem. I guess what happens is

  • bitvec reads from the start position until the end of the first word (00_0111)
    • this value is zeroextended to 0000_0111 (aka 0x7) and appended to the output
  • bitvec reads the remaining bits from the second word (01)
    • this value is shifted by 6 to 0100_0000 (aka 0x80), because the bitvec ended 6 bits before the end of the current word, and the result is appended to the output

@myrrlyn could you clarify what the expected output is? I guess there must be tests covering reads across word boundaries, therefore this behaviour might be intended (?)

Trolldemorted avatar Mar 09 '24 10:03 Trolldemorted