#define SET_BIT(byte, bit) (byte |= (1 << bit))
#define CLEAR_BIT(byte,bit) (byte &= ~(1 << bit))
uint8_t data [5];
for (int i = 0; i < 5; ++i)
{
for(int j = 7; j >= 0; --j)
{
if (some condition)
--> CLEAR_BIT(data[i],j);
else if (some condition)
--> SET_BIT(data[i],j);
}
}
I want to understand how is bit manipulation taking place in arrowed lines?
When I declare uint8_t data [5]; does it mean... An array of name data and I can store 5 uint8_t value(char basically) in it and in the location of each array index there will be 8 bits.Like This
Because you use define
the line SET_BIT(data[i],j)
is being replaces during pre-processing with data[i] |= (1 << j)
(consider using inline
instead and have the benefit of type safety).
The best way to understand is to make an example of a simple case (avoid these nested loops).
(lets assume you're data array is initialized to 0, which is not currently the case)
for instance: i = 2, j = 3
:
1 << 3
= 00001000
shift the value 1 three times to the left , data[2]
= 00000000
|=
is a bit-wise operator, there for - a logical OR
between each corresponding bits will take place and data[2]
will be equal to 00001000
now, for i = 2, j = 6
:
1 << 6
= 01000000
, data[2] = 00001000
A bit-wise OR
will take place and yield 1
for bits 3,6.
data[2]
will be equal to 01001000
.
With this example you can understand the more complex example.