Parse an array of bits (`BitArray`) to an integer

Something like this:

function bitarray_to_vector_of_bits(a)
    len = size(a, 1)
    return [SBitVector{len}(sum(i -> UInt(col[i]) << (i-1), 1:len)) for col in eachcol(a)]
end

I see. So do you know why do I get numbers that are different from a straight forward calculation?

The code is assuming that each column has 64 elements, and it’s reinterpreting to Int64 which can take both negative and positive values.

If you want a different type of integer, use e.g. UInt64. Fixing the number of elements per column is harder.

Here is a fast version with zero allocations. You can also control the output through the optional argument s. If the array has more than 63 elements, you can set s = 0.0 or s = big(0) to avoid Int overflow.

function bitarr_to_int5(arr,s=0)
    v = 1
    for i in view(arr,length(arr):-1:1)
        s += v*i
        v <<= 1
    end 
    s
end

arr = BitArray(rand(0:1,50))
@btime bitarr_to_int($arr)
@btime bitarr_to_int2($arr)

  391.547 ns (2 allocations: 992 bytes)
  51.622 ns (0 allocations: 0 bytes)
3 Likes