How to read individual bits from an array?

Suppose I have a dynamically allocated array.

int* array=new int[10]

This is 10 * 4 = 40 bytes or 10 * 32 = 320 bits. I want to read the second bit of the 30th byte or 242th bit. What is the easiest way to do this? I know that I can access the 30th byte using the array [30], but access to individual bits is more complicated.

+5
source share
6 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;
}
+6
source

it works!

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

conclusion:

010101010101010101010101010101010111111111110000000011111111000000000000

Be careful with the Endian!

+1
source

-, , ( ). : 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;

:

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

:

array[wordIndex] |= 1 << bitIndex;

reset:

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

, n vector<bool> boost::dynamic_bitset , - .

+1

EDITED - int 32 , 8 uchar.

int pos = 241; // I start at index 0
bool bit242 = (array[pos/32] >> (pos%32)) & 1;
0

- :

!((array[30] & 2) == 0)

array [30] - .

& 2 - , (2 = 00000010)

== 0 will check if the result of mask 0

! will deny this result, because we check if it is equal to 1 ... 0.

0
source

You need bit operations here ...

if(array[5] & 0x1)
{
//the first bit in array[5] is 1
}
else
{
//the first bit is 0
}

if(array[5] & 0x8)
{
//the 4th bit in array[5] is 1
}
else
{
//the 4th bit is 0
}

0x8 - 00001000 in binary format. Performing an engagement mask all other bits and lets you see if bit 1 is 0 or 0.

int is usually 32 bits, so you need to do some arithmetic to get a certain number of bits in the whole array.

0
source

All Articles