# Generate vector of binary digits from int

Is there an easy way to generate a vector of binary digits from an int?

For example, suppose I want a 4-bit representation of the integer `3` (`0b0011`). Something like:

``````julia> bin_to_vec(3,4)
[0, 0, 1, 1]
``````

where I can optionally specify how many bits to pad to (in this case 4).

I’m hoping to use this vector as a mask for some additional computation.

Thanks!

Not very elegant since it goes fron Int to String back to Int and then Vector, but it works:

``````julia> [Int(x)-48 for x in string(3, base = 2, pad = 4)]
4-element Vector{Int64}:
0
0
1
1
``````

For masking operations, though, a `BitVector` might be more appropriate:

``````BitVector(x == '0' ? false : true for x in string(3, base = 2, pad = 4))
4-element BitVector:
0
0
1
1
``````
2 Likes

You can use `digits`, but note the returned vector is in reversed order (least significant bit first)

``````digits(3, base=2, pad=4)
``````
5 Likes

How do you want the output vector to be? A vector of `Int`s, a vector of `Bool`s, or could it be a `BitVector`? How are going to use it?

And is it always a 4-bit number, or could the input/output be other lengths as well?

``````
bitvec(n)=n>1 ? [bitvec(n÷2);Bool(n%2)] : Bool

``````
1 Like
``````julia> bin_to_vec(x,n) = [ (x >> i) & 1 for i in n-1:-1:0]
bin_to_vec (generic function with 1 method)

julia> bin_to_vec(3,4)
4-element Vector{Int64}:
0
0
1
1
``````

Is this good? (shifts and ANDs are fast, so should be efficient).

3 Likes
``````b2v(n,p)=n>1 ? [b2v(n>>1,p-1);Bool(n&1)] : [fill(false,max(0,p-1)); true]
``````

The best approach here might be to not do anything. Rather than getting a vector of `Bool` to mask with, you can just use a loop and mask with bitshifts.

3 Likes