Alternatives to 'bitvec' and 'bit-vec' that support shifting right/left (LSR/LSL)

I'm trying to write an algorithm that requires a large bit vector where I can easily shift bits to the left efficiently. 'bitvec' and 'bit-vec' do not appear to support that functionality. Are there any other crates that anyone knows about that support this functionality or do I need to roll my own?

Did you miss shift_left? Or dont you want to work inplace?


Yes, I did miss that somehow. Aaaaargggghhhh! I knew it should be there I just somehow missed it. One question though, the documentation says that shift_left shifts bits towards 0 (lsb) and shift_right towards max (msb). That sounds backwards. Is the documentation correct? Am I reading it wrong?

Ok, shift_left/shift_right seem to solve my problem. Am I using the API correctly here? Or is there better ways to do this?

    fn compute_subset_sum_flags(data: Vec<i32>) -> BitVec {
        let mut subset_sum_flags = bitvec![0_u64;100_000];
        subset_sum_flags.set(0, true);
        for val in data {
            let original_subset_sum_flags = subset_sum_flags.clone();
            if val >= 0 {
                subset_sum_flags.shift_left(val as usize);
            } else {
                subset_sum_flags.shift_right(-val as usize);
            subset_sum_flags |= original_subset_sum_flags;

It appears the documentation for shift_left/shift_right is wrong AND that they work backwards of expectations if you weren't reading the docs fully. The documentation says that shift_left shifts down towards zero (which is backwards of expectation) but then the sample code with assertions shows that it shifted the bits up. The opposite is the case for shift_right in the documentation. Or am I reading it wrong?

I had to switch shift_left and shift_right in my code above to have it work, but then it seems to read backwards. I would expect shift_left to perform a LSL (Logical Shift Left) and shift_right to perform a LSR (Logical Shift Right). It appears to do the opposite.

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.