# Some bit manipulations

**URL:** <https://discourse.julialang.org/t/some-bit-manipulations/3772>\
**Category:** New to Julia\
**Created:** [May 17, 2017, 2:45pm UTC](https://discourse.julialang.org/t/some-bit-manipulations/3772 "2017-05-17T14:45:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ndbecker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ndbecker/32/10829_2.png) [@ndbecker](https://discourse.julialang.org/u/ndbecker)\
**Post date:** [May 17, 2017, 2:45pm UTC](https://discourse.julialang.org/t/some-bit-manipulations/3772/1 "2017-05-17T14:45:17Z")

</div>

I’m trying to port to julia some python code that produces this:  
ind0: [[0 2 4 6]  
[0 1 4 5]  
[0 1 2 3]]  
ind1: [[1 3 5 7]  
[2 3 6 7]  
[4 5 6 7]]

For a range of 0:7, the code produces 2 2d arrays. For any value j in that range, that value is in ind[i,:] if j has a 1 in bit position i. So the 1st row of ind1 is all values that have a 1 in bit0, the second row of ind1 is all values that have a 1 in bit1…

I tried this code:

```julia
    function gen_ind(_size, bits)
        all_syms = Array(0:_size-1)
        all_bits = Array(0:bits-1)
        bit_mask = (reshape(all_syms, (size(all_syms)[1],1)) .>> reshape(all_bits, (1, size(all_bits)[1]))) .& 1
        ind1 = [find(bit_mask[:,i]) for i in 1:bits]
    end
    gen_ind(8,3)

```

It sort of works, but it returns

```julia
[find(bit_mask[:,i]) for i in 1:3]
3-element Array{Array{Int64,1},1}:
 [2, 4, 6, 8]
 [3, 4, 7, 8]
 [5, 6, 7, 8]

```

an Array{Array…}, where I wanted Array{Int64,2}.  
Any suggestions? Doesn’t need to be efficient - only used once at program start.

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [May 17, 2017, 3:42pm UTC](https://discourse.julialang.org/t/some-bit-manipulations/3772/2 "2017-05-17T15:42:43Z")

</div>

You can do `hcat([find(bit_mask[:,i]) for i in 1:bits]...)`

to get:

```julia
gen_ind(8,3)
4×3 Array{Int64,2}:
 2 3 5
 4 4 6
 6 7 7
 8 8 8

```

---

<div class="post-metadata">

**Author:** ![ndbecker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ndbecker/32/10829_2.png) [@ndbecker](https://discourse.julialang.org/u/ndbecker)\
**Post date:** [May 17, 2017, 6:11pm UTC](https://discourse.julialang.org/t/some-bit-manipulations/3772/3 "2017-05-17T18:11:42Z")

</div>

I suppose I’m better off learning to leave the vectorized functions, and just do:

```julia
function ind(bits, value)
    syms = 2^bits
    rows = []
    for bit in 0:bits-1
        row = []
        for sym in 0:syms-1
            if((sym >> bit) & 1 == value)
                push!(row, sym)
            end
        end
        push!(rows, row)
    end
    return hcat(rows...)'
end

```
