Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packing an array of booleans into an int in Java

Tags:

java

I'm not very familiar with all the bit shifting and masks that are involved with the process but I have a vague idea.

I'm looking for a way to pack around 30 booleans into an int or long so I can send the packed data through one data type, rather than sending across 30 separate booleans. Either this if it's possible, or the use of a bit set might help. I was wondering if someone could give me a little insight into how to go about packing the values.

like image 713
kbz Avatar asked Jan 08 '23 13:01

kbz


2 Answers

If you have an int (32 bits), you can set, clear, and check the N'th (0-31) bit like this:

int bits = 0;

// Set bit n
bits |= 1 << n;

// Clear bit n
bits &= (1 << n) ^ -1;

// Check bit n
if ((bits & 1 << n) != 0) { /*bit was set*/ }

So, to convert a boolean array into a bitmask:

boolean[] bools = /*allocated elsewhere, max. length: 32*/;

int bits = 0;
for (int i = 0; i < bools.length; i++)
    if (bools[i])
        bits |= 1 << i;

And to convert a bitmask to a boolean array:

int bits = /*assigned elsewhere*/;

boolean[] bools = new boolean[30]; /*max. length: 32*/
for (int i = 0; i < bools.length; i++)
    if ((bits & 1 << i) != 0)
        bools[i] = true;
like image 166
Andreas Avatar answered Jan 17 '23 16:01

Andreas


A boolean represents a bit of information, 30 booleans represent 30 bits of information. Build an int (32 bits), send it, job done.

May not be the best approach, but just to give you an idea

    int i=0;
    boolean[]a = {true,false,true,false,false,false,false};
    for(boolean b:a)i=i*2+(b?1:0);
    System.out.println(Integer.toBinaryString(i));

prints

    1010000
like image 45
Luigi Cortese Avatar answered Jan 17 '23 15:01

Luigi Cortese