# Convert integer to bits array

The proper way is

``````julia> function bm(u)
res =BitVector(undef, sizeof(u)*8)
res.chunks[1] = u%UInt64
res
end
julia> bm(0x05)
8-element BitArray{1}:
true
false
true
false
false
false
false
false
``````

This is not exactly what you asked for: The bit pattern is reversed (little endian bitorder). You can use this code to convert to big endian (better than the llvm bitreverse intrinsic):

``````julia> function revbits(z::UInt8)
z = (((z & 0xaa) >>  1) | ((z & 0x55) <<  1))
z = (((z & 0xcc) >>  2) | ((z & 0x33) <<  2))
z = (((z & 0xf0) >>  4) | ((z & 0x0f) <<  4))
return z
end

julia> function revbits(z::UInt16)
z = (((z & 0xaaaa) >>  1) | ((z & 0x5555) <<  1))
z = (((z & 0xcccc) >>  2) | ((z & 0x3333) <<  2))
z = (((z & 0xf0f0) >>  4) | ((z & 0x0f0f) <<  4))
return ntoh(z)
end

julia> function revbits(z::UInt32)
z = (((z & 0xaaaaaaaa) >>  1) | ((z & 0x55555555) <<  1))
z = (((z & 0xcccccccc) >>  2) | ((z & 0x33333333) <<  2))
z = (((z & 0xf0f0f0f0) >>  4) | ((z & 0x0f0f0f0f) <<  4))
return ntoh(z)
end

julia> function revbits(z::UInt64)
z = (((z & 0xaaaaaaaaaaaaaaaa) >>  1) | ((z & 0x5555555555555555) <<  1))
z = (((z & 0xcccccccccccccccc) >>  2) | ((z & 0x3333333333333333) <<  2))
z = (((z & 0xf0f0f0f0f0f0f0f0) >>  4) | ((z & 0x0f0f0f0f0f0f0f0f) <<  4))
return ntoh(z)
end
``````

and use

``````julia> function revbm(u)
res =BitVector(undef, sizeof(u)*8)
res.chunks[1] = revbits(unsigned(u))%UInt64
res
end
julia> revbm(Int8(5))
8-element BitArray{1}:
false
false
false
false
false
true
false
true
``````
6 Likes