bits array to bytes - java

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

Answers


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;
}

Need Your Help

How to extend native JavaScript array in TypeScript

javascript typescript

Is there any way to inherit a class from JS native function.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.