Iterating on bits


#1

How do I iterate over the bits of a UInt8, UInt16 or UInt64? I tried

julia> for x in digits(Bool, UInt16(17),2) ...

It works but it creates an intermediate array, I am not sure this is how it should be done.


#2

There is the digits! function which at least allow you to re-use the allocated array. I’ve a not-yet-published package for this kind of things, I’ll try to remember to link it here when it’s ready.


#3

Do you actually want to iterate over the bits? Or the digits? Here’s an example of a simple BitIterator:

struct BitIterator{T}
    val::T
end
Base.start(b::BitIterator) = 1
Base.next(b::BitIterator{T}, i) where {T} = ((b.val & T(2)^(sizeof(T) * 8 - i)) == 1, i + 1)
nbits(T) = sizeof(T) * 8
Base.done(b::BitIterator{T}, i) where {T} = i > nbits(T)

Which can be used like

julia> b = BitIterator(UInt8(1))
BitIterator{UInt8}(0x01)

julia> bits(UInt8(1))
"00000001"

julia> for i in b
           println(i)
       end
Loop variable "i" overwrites a variable in an enclosing scope. In the future the variable will be local to the loop instead.
false
false
false
false
false
false
false
true

julia> b = BitIterator(UInt64(1))
BitIterator{UInt64}(0x0000000000000001)

julia> bits(UInt64(1))
"0000000000000000000000000000000000000000000000000000000000000001"

julia> for i in b
           println(i)
       end
Loop variable "i" overwrites a variable in an enclosing scope. In the future the variable will be local to the loop instead.
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
true