I’m still not sure I understand what you want to do, but if the arrays just represent the bits in an integer then this is easy:
As several people have suggested, don’t bother creating the arrays, just create the integers and arrange the integers. The built-in function count_ones
gives you the number of 1s in the binary representation of the integer, and sort
will sort them by that:
julia> sort(1:16, by=count_ones)
16-element Vector{Int64}:
1
2
4
8
16
3
5
6
9
10
12
7
11
13
14
15
To see what this looks like in binary, we can also use bitstring
to show the 1s and 0s (converting to UInt8
just to make things easier to read):
julia> println.(bitstring.(UInt8.(sort(1:16, by=count_ones))));
00000001
00000010
00000100
00001000
00010000
00000011
00000101
00000110
00001001
00001010
00001100
00000111
00001011
00001101
00001110
00001111
A lot of the operations you’re talking about on these arrays of bits can be done directly on integers, because they’re very common operations. For example, xor(3,5)
just works out of the box. They’re called “bitwise operators”. It’s standard to use unsigned integers (UInt
and friends) so you don’t have to worry about the sign bit. More generally, “bit twiddling” also works on integers. I wouldn’t be surprised if there are more, but there’s at least one package just for some bit twiddling tricks. There’s also the classic page of “Bit Twiddling Hacks” that any good nerd should know about.
One example that might be relevant for you is from your other question. I would translate
a = [0, 0, 0, 1, 0, 1, 0, 1]
b = [1, 2, 3, 5]
into the integer equivalents (ignoring a possible endianness ambiguity)
a = 21
b = 232 # Has 1s in binary representation at indices [1,2,3,5]
Then the sum over values in a
at indices b
translates simply to
count_ones(a & b)
(Bit twiddlers would call b
the “mask”.)