I use a byte to store some flag like 10101010
, and I would like to know how to verify that a specific bit is at 1
or 0
.
As an extension of @Daoks 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 what you are wanting to do is:
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.
You can do as Daok says and you make a bit to bit OR to the resulting of the previous AND operation. In this case you will have a final result of 1 or 0.
Use a bitwise (not logical!) and to compare the value against a bitmask.
if (var & 0x08) {
/* the fourth bit is set */
}
byte THIRDBIT = 4; // 4 = 00000100 i.e third bit is set
int isThirdBitSet(byte in) {
return in & THIRDBIT; // Returns 1 if the third bit is set, 0 otherwise
}
Traditionally, to check if the lowest bit is set, this will look something like:
int MY_FLAG = 0x0001;
if ((value & MY_FLAG) == MY_FLAG)
doSomething();
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.