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
0b0011). Something like:
[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.
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)]
For masking operations, though, a
BitVector might be more appropriate:
BitVector(x == '0' ? false : true for x in string(3, base = 2, pad = 4))
You can use
digits, but note the returned vector is in reversed order (least significant bit first)
digits(3, base=2, pad=4)
How do you want the output vector to be? A vector of
Ints, a vector of
Bools, 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
julia> bin_to_vec(x,n) = [ (x >> i) & 1 for i in n-1:-1:0]
bin_to_vec (generic function with 1 method)
Is this good? (shifts and ANDs are fast, so should be efficient).
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.