# Convert integer to bits array

**URL:** <https://discourse.julialang.org/t/convert-integer-to-bits-array/26663>\
**Category:** New to Julia\
**Created:** [July 23, 2019, 3:06am UTC](https://discourse.julialang.org/t/convert-integer-to-bits-array/26663 "2019-07-23T03:06:33Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)\
**Post date:** [July 23, 2019, 7:23pm UTC](https://discourse.julialang.org/t/convert-integer-to-bits-array/26663/7 "2019-07-23T19:23:58Z")

</div>

The proper way is

```julia
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](https://discourse.julialang.org/t/covert-bitarray-to-int64/9193/4) code to convert to big endian (better than the llvm bitreverse intrinsic):

```julia
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
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

```

---

_[View the full topic](https://discourse.julialang.org/t/convert-integer-to-bits-array/26663)._
