0

how can I store a sequence of bits in an array of bytes[] ? in more detail: I have an array

byte[] bytes;

how will I store individual values (0s and 1s) in a single byte of the array? I am looking for something like:

bit[] bits = new bit[8];
bits[0] = 1;
bits[3] = 1;
bytes[3] = bits[];

I hope that makes sense. thanks

7
  • Could you put the 0s and 1s into a String and use Byte.parseByte with a radix of 2? Commented Feb 28, 2014 at 2:37
  • 1
    I need to make alterations to the byte sequence every now and then so it wont be a good idea to do it like that as i would have to rebuild the sequence over and over instead of just adding/swapping the new value to the required index posission Commented Feb 28, 2014 at 2:40
  • @DavidWallace Yes, but it is rather memory inefficient. Commented Feb 28, 2014 at 2:41
  • Yes, but OP hasn't told us what his/her input is. Maybe he/she is reading a file full of 0s and 1s, so already has String. In which case, there's no real cost in memory (at least in Java 6; Java 7 manages memory differently for strings). Commented Feb 28, 2014 at 2:43
  • to make it more clear I am using an array of bytes because I am storing binary values of strings in the rest of the indexes. it is just one or two indexes that I need to store bits in them. Commented Feb 28, 2014 at 2:49

2 Answers 2

1
void setBit(int[] array, int index, boolean value) {
    int x = index / 32;
    int y = index % 32;
    int mask = 1 << y;
    if (value) {
        array[x] |= mask;
    }
    else {
        array[x] &= (0xFFFFFFFF ^ mask);
    }
}

boolean getBit(int[] array, int index) {
    int x = index / 32;
    int y = index % 32;
    int mask = 1 << y;
    return (array[x] & mask) != 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

A boolean can be used to represent a bit, but it takes up more memory. You could use bitwise operators to save on memory, here is an example:

int n = 0;
n |= 1 << 1; // Set bit 1 to true, n is 2
n |= 1 << 3; // Set bit 3 to true, n is 10
bool b0 = n & (1 << 3) > 0; // True
n &= 1 << 3; // Set bit 3 to false, n is 2
bool b1 = n & (1 << 1) > 0; // True
bool b2 = n & (1 << 2) > 0; // False
bool b3 = n & (1 << 3) > 0; // False

3 Comments

You could replace each Math.pow with 1 << something
It is more a matter of memory in my case than a matter of true & false so a Boolean wont work for me..
Bitwise operators will be the most memory efficient way possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.