How can I check my byte flag, verifying that a specific bit is at 1 or 0?
Here's a function that can be used to test any desired bit:
bool is_bit_set(unsigned value, unsigned bitindex)
{
return (value & (1 << bitindex)) != 0;
}
A bit of explanation:
The left shift operator (<<) is used to create a bit mask. (1 << 0) will be equal to 00000001, (1 << 1) will be equal to 00000010, (1 << 3) will be equal to 00001000, etc. So a shift of 0 tests the rightmost bit. A shift of 31 would be the leftmost bit of a 32-bit value.
The bitwise-and operator (&) gives a result where all the bits that are 1 on both sides are set. Examples: 1111 & 0001 = 0001; 1111 & 0010 == 0010; 0000 & 0001 = 0000. So, the expression (value & (1 << bitindex)) will return the bitmask if the associated bit is 1 in value, or will return 0 if the associated bit is 0.
Finally, we just check whether the result is non-zero. (This could actually be left out, but I like to make it explicit.)
You can use an AND operator. The example you have: 10101010 and you want to check the third bit you can do: (10101010 AND 00100000) and if you get 00100000 you know that you have the flag at the third position to 1.
As an extension of Patrick Desjardins' answer:
When doing bit-manipulation it really helps to have a very solid knowledge of bitwise operators.
Also the bitwise "AND" operator in C is &
, so you want to do this:
unsigned char a = 0xAA; // 10101010 in hex
unsigned char b = (1 << bitpos); // Where bitpos is the position you want to check
if(a & b) {
//bit set
}
else {
//not set
}
Above I used the bitwise "AND" (& in C) to check whether a particular bit was set or not. I also used two different ways of formulating binary numbers. I highly recommend you check out the Wikipedia link above.
Kristopher Johnson's answer is very good if you like working with individual fields like this. I prefer to make the code easier to read by using bit fields in C.
For example:
struct fieldsample
{
unsigned short field1 : 1;
unsigned short field2 : 1;
unsigned short field3 : 1;
unsigned short field4 : 1;
}
Here you have a simple struct with four fields, each 1 bit in size. Then you can write your code using simple structure access.
void codesample()
{
//Declare the struct on the stack.
fieldsample fields;
//Initialize values.
fields.f1 = 1;
fields.f2 = 0;
fields.f3 = 0;
fields.f4 = 1;
...
//Check the value of a field.
if(fields.f1 == 1) {}
...
}
You get the same small size advantage, plus readable code because you can give your fields meaningful names inside the structure.