# Scanning bit state in a binary number

Hi,

I just wrote a program to practice bit masking and bitwise operands. The reason I want to do this is I currently have a library with multiple outputs that are in an on off state. Right now the state is represented as an integer but I suppose I could store up to 8 output states in a single byte with a little more sophistication. I can also save memory. Here is my program:

``````byte value = B00100100;
byte currentbit;

void setup() {
Serial.begin(9600);

}

void loop() {
delay(500);
Serial.println(value, BIN);
delay(500);
Serial.println();
Serial.println(currentbit, BIN);
delay(200);
}
Serial.println();
}
``````

When run the output is the following:

100100

0
0
100
0
0
100000
0
0

What must I do to my code such that the bit state of that single location is printed and doesn’t take into account the number of bits before it. I would like my code to print in the following manner:

100100

0
0
1
0
0
1
0
0

Thank you for taking a look at this.

Try:

``````byte value = B00100100;
byte currentbit;

void setup() {
Serial.begin(9600);

}

void loop() {
delay(500);
Serial.println(value, BIN);
delay(500);
Serial.println();
if(currentbit)
{
currentbit = 1;
}

Serial.println(currentbit, BIN);
delay(200);
}
Serial.println();
while(1); // stop here
}
``````

You can also cast to bool

``````currentbit= (bool) (value & mask);
``````

Or use bitRead if you want a simpler method

``````for ( uint8_t i = 0; i < 8; i++ )
currentbit = bitRead( value, i );
``````

Also you may be interested by a struct of bit fields.

@guix

currentbit= (bool) (value & mask) ;

Nice.