How to convert bytes to `BitVector`?

I’m handed some bytes by a file format, and each bit represent a Bool – now, I know a little bit about how our BitVector works, so I have some snippet that’s quite fragile:

    total_num_elements = ...
    # pad to nearest 8*k bytes because each chunk needs to be UInt64
    bytes = ...
    append!(bytes, zeros(eltype(bytes), 8 - rem(total_num_elements, 8)))
    chunks = reinterpret(UInt64, bytes)

    res = BitVector(undef, total_num_elements)
    copyto!(res.chunks, chunks) # don't want jam ReinterpretArray into BitVector

but this fails for:

total_num_elements = 10000
bytes = rand(UInt8, 1250)

I can probably do a if-else to gate the logic so if we happen to land on divisible input, we don’t pad it. But in general I’m wondering if there’s a better way

actually, maybe the fix is that this should be

(64 - rem(total_num_elements, 64)) \div 8
1 Like