# Get every bit out of a string ?

Say I have this :

``````char bits[5] = "1011";
``````

I would like to get a binary variable for each one of the bits, to set my outputs, so - 1 , 0 ,1 ,1

The only way I see is to loop on every char, and turn it into boolean.
Is that the most efficient way ? if so , which way is the best to turn it to boolean ?

sprintf ? atoi ?

I have found this ,

``````   int var = get_value_between_zero_and_six();
digitalWrite(11, HIGH && (var & B00001000));
digitalWrite(12, HIGH && (var & B00000100));
digitalWrite(13, HIGH && (var & B00000010));
digitalWrite(14, HIGH && (var & B00000001));
``````

But I don't understand how it works, I know what '&' will provide = an 'AND' operation, but from what I know digitalWrite gets pin and a state - LOW/HIGH, so how this code even works ? I would get it if you output that number to a PORT, not a single pin..

var & B...... will result in zero, if the corresponding bit(s) in var is not set. So, it is false. If the bit is set, the result will be non-zero and thus be interpreted as true.

but from what I know digitalWrite gets pin and a state - LOW/HIGH, so how this code even works ?

Because a HIGH AND LOW gives you a LOW. Also a HIGH and HIGH gives you a HIGH. But that code uses a && which is a comparison operation not a bit wise AND.

It is poor code because you could just write.

``````digitalWrite(11, var & B00001000);
``````

OR even

``````digitalWrite(11, var & 0x08);
``````

Even then the code is very verbose and can be shortened by using an array to hold the pin number and a shift operator ( that is << ) to generate the mask ( the number you are doing the bitwise and with. )

Maybe I'm not understanding the problem, but what about something like:

``````void setup() {
char bits[] = "1011";
int pins = 11;
Serial.begin(9600);

for (int i = 0; bits[i]; i++) {
// ditialWrite(pins, bits[i] - '0');
Serial.print("For pin ");
Serial.print(pins);
Serial.print(" output is: ");
Serial.println( (int) bits[i] - '0');
pins++;
}
}

void loop() {
}
``````