Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read individual bits from an array?

Tags:

c++

binary

Lets say i have an array dynamically allocated.

int* array=new int[10]

That is 10*4=40 bytes or 10*32=320 bits. I want to read the 2nd bit of the 30th byte or 242nd bit. What is the easiest way to do so? I know I can access the 30th byte using array[30] but accessing individual bits is more tricky.

like image 961
Jake Avatar asked Mar 21 '11 10:03

Jake


People also ask

How do you read a single bit?

To read a bit at a specific position, you must mask out all other bits in the value. The operator that assists in that process is the bitwise & (and). After you mask out all the other bits, the value that remains is either zero or some other value.

How do you read a byte from a bit?

The first method is to use a mask to extract the value of a bit as in: msb = ( byte & 0x80 ) != 0x00; This will set the value of msb to the value of the most significant bit of byte.

Can you execute bit array in C language?

This is a C Program to implement Bit Array. A bit array is an array data structure that compactly stores bits. It can be used to implement a simple set data structure. A bit array is effective at exploiting bit-level parallelism in hardware to perform operations quickly.

How many bits are in an array?

It stores bits using an array of type int (each element in the array usually represents 32 bits).


3 Answers

bool bitset(void const * data, int bitindex) {
  int byte = bitindex / 8;
  int bit = bitindex % 8;
  unsigned char const * u = (unsigned char const *) data;
  return (u[byte] & (1<<bit)) != 0;
}
like image 183
Erik Avatar answered Oct 22 '22 10:10

Erik


this is working !

#define GET_BIT(p, n) ((((unsigned char *)p)[n/8] >> (n%8)) & 0x01)

int main()
{
    int myArray[2] = { 0xaaaaaaaa, 0x00ff00ff };
    for( int i =0 ; i < 2*32 ; i++ )
        printf("%d", GET_BIT(myArray, i));
    return 0;
}

ouput :

0101010101010101010101010101010111111111000000001111111100000000

Be carefull of the endiannes !

like image 41
chris Avatar answered Oct 22 '22 10:10

chris


First, if you're doing bitwise operations, it's usually preferable to make the elements an unsigned integral type (although in this case, it really doesn't make that much difference). As for accessing the bits: to access bit i in an array of n int's:

static int const bitsPerWord = sizeof(int) * CHAR_BIT;
assert( i >= 0 && i < n * bitsPerWord );
int wordIndex = i / bitsPerWord;
int bitIndex = i % bitsPerWord;

then to read:

return (array[wordIndex] & (1 << bitIndex)) != 0;

to set:

array[wordIndex] |= 1 << bitIndex;

and to reset:

array[wordIndex] &= ~(1 << bitIndex);

Or you can use bitset, if n is constant, or vector<bool> or boost::dynamic_bitset if it's not, and let someone else do the work.

like image 23
James Kanze Avatar answered Oct 22 '22 11:10

James Kanze