Search code examples
arraysjuliabitset

Convert an array of UInt64 into a BitVector


I've recently discovered that I can get the 'backing array' of UInt64 for a BitVector using chunks. However, I would like to go the opposite way - given a one-dimensional array of UInt64, construct a BitVector using some function foo such that

foo(x.chunks) == x

Does such a function exist?


Solution

  • Would something like this work?

    function foo(v::Vector{UInt64})
        siz = sizeof(v)
        bv = falses(siz << 6)
        unsafe_copyto!(reinterpret(Ptr{UInt64}, pointer(bv.chunks)), pointer(v), siz)
        bv
    end
    

    They also provide an overload to set the number of bits in the resulting BitVector if required.

    EDIT: The use of unsafe_copyto! indicates that the code may not perform extensive safety checks and relies on low-level memory operations. Care should be taken when using such functions to ensure that memory is accessed and manipulated safely.

    Another way of doing what you're asking:

    function bar{T}(v::Vector{T})
        siz = sizeof(T) * length(v) * 8  # Calculate size in bits
        bv = BitVector(siz)              # Create a BitVector of the appropriate size
        bv .= reinterpret(BitArray, v)   # Use a broadcast assignment to copy the data
        return bv
    end