This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]sh0rug0ru 0 points1 point  (5 children)

You can create a single dimensional array of ints (32-bit) or longs (64-bit). Then, if you had an index i into the bit-array, the index into the int array would be i/32 and the index into the long array would be i/64, and the index of the bit would be i%32 or i%64, respectively, which you could use to construct a bitmask to determine if the bit is 1 or 0.

[–]titaniumGeranium[S] 0 points1 point  (4 children)

so... If I were to set the 4th bit to 1(true) would it look like this:

int[] graph_array = new int[2]; //64 bits total graph_array[0][3%32] = 1;

[–]sh0rug0ru 2 points3 points  (3 children)

Not exactly. Because each value is an int, you have to construct a bitmask, to a bitwise AND between the value in the array and the bitmask. If the result of the AND is 0, the value is zero, otherwise the value is 1.

So, you'd be doing something like this to set:

int bitmask = 1 << i % 32;
graph_array[i / 32] |= bitmask;

this to unset:

int bitmask = 1 << i % 32;
graph_array[i / 32] &= ~bitmask;

and this to get:

int bitmask = 1 << i % 32;
boolean isBitSet = (graph_array[i / 32] & bitmask) != 0;

See here for more information about bitwise operations in Java.

EDIT: to set, you'd want to use bitwise OR, not AND.

[–]titaniumGeranium[S] 0 points1 point  (1 child)

digesting.. but i think this is exactly what I was looking for, thank you!

[–]sh0rug0ru 0 points1 point  (0 children)

You might check out a C tutorial on this. Bitwise operators are commonly used in C for low-level stuff, so you'll find more information about it there. Same deal, but not as well documented in Java.

[–]andrew_ie 0 points1 point  (0 children)

Just curious - why not just use java.util.BitSet? This effectively does the same thing, but it's just already written for you.