0

While doing my homework, I had a question about bits.

How does save bits in an array of int8_t?

And How can I access these bits?

Here are some example code

void someting_with_bits(int8_t bit_array[])
{
  //Do sometings...
}

If there is a function like this,

when I call bit_array[0], do I return 8 length bits like 11100011?

If that be so, How can I access the first bits of bit_array[0]?

mimic
  • 85
  • 1
  • 7
  • Please give some more details about what will be stored in the `bit_array` – KagurazakaKotori Nov 02 '19 at 03:40
  • I think there will be saved like this 11100011 in one array I mean bit_array[0]. – mimic Nov 02 '19 at 03:41
  • The name of a variable has no impact on its type. Naming a variable "`bit_array`" does not make it an array whose elements are bits. Your question could probably be rewritten without the array aspect: given an `int8_t` (better yet, an `uint8_t`), how can you access the individual bits? – JaMiT Nov 02 '19 at 04:45
  • Possible duplicate of [Access individual bits in a char c++](https://stackoverflow.com/questions/9531214/access-individual-bits-in-a-char-c) – JaMiT Nov 02 '19 at 04:49
  • Does this answer your question? [How do you set, clear, and toggle a single bit?](https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit) – phuclv Nov 02 '19 at 07:18

2 Answers2

1

Yes, it will be saved like 11000011 in one array block.

To access a specified bit, you need to shift it and then AND it with a special mask.

For example, to access the highest bit of bit_array[0]:

int8_t highest_bit = (bit_array[0] >> 7) & 0x1;

to access the highest 4 bits of bit_array[0]:

int8_t highest_4_bits = (bit_array[0] >> 4) & 0xf;
KagurazakaKotori
  • 562
  • 4
  • 14
0

If you want to access individual bits of each integer, you can do some bit manipulations. for example if you want to check 3rd least significant bit of an integer, AND it with 0x4(100). Also you can right shift your int 2 times and then AND it with 0x1. for example to check the 5th least significant bit of integer with index 3 in your array:

bool theBit = (bit_array[3] >> 4) & 0x1;

Of course you can use bitset. http://www.cplusplus.com/reference/bitset/bitset/

for example to access 3rd least significant bit of a 32 bit integer (don't forget to include bitset header):

int32_t number = 233;
std::bitset<32> bits(number);
std::cout << "The 3rd ls bit is: " << bits[2] << std::endl;