Then I can compare ALL the bits together with a simple test.
if ( z==x)
But I only want to compare the 4 least significant (rightmost) bits. I've done it using bitRead() but I'd like to do it like a proper programmer so I think I ought to be using bitmasks and XORs and something (no idea what these words mean, copied them from someone smarter than me!)
// code before setup (i.e. global)
byte maskArray[] = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,}; // const if you want
// code in loop:
for (x=0; x<0x81; x=x+1){
if ((data & maskArray[x]) == 0){
// bit is 0, do something
}
else {
// bit is 1, do something else
}
void setup() {
}
void loop() {
byte z = 0b11111111;
byte x = 0b00001111;
int result = 0;
result = z && x;
result << 12; //Shift 12 bytes left
result >> 12; // Shift back..
byte done = result;
}
How so?
if bit 0 is high:
0bYYYYYYY1 & 0b00000001 =1, where Y is a don't care bit
if bit 0 is low:
0bYYYYYYY0 & 0b00000001 = 0
Continue with right hand side marching a 1 across to test all the bits.
Another example:
if bit 3 is high:
0bYYYY1YYY & 0b00001000 = 0b00001000, or !0, where Y is a don't care bit
if bit 3 is low:
0bYYYY0YYY & 0b00001000 = 0
I have used this technique successfully before, looking for a 0, or a Not 0, so the actual value does not matter.
But I only want to compare the 4 least significant (rightmost) bits. I've done it using bitRead() but I'd like to do it like a proper programmer so I think I ought to be using bitmasks and XORs and something (no idea what these words mean, copied them from someone smarter than me!)
several ways, of course. Two are:
if((x&0b1111) == (z&0b1111))
if( ((x^z) & 0b1111) == 0)
I always put all the parenthesis around bit-fiddling operations, as operator precedence for these operators is sometimes a bit unexpected.
CrossRoads:
How so?
if bit 0 is high:
0bYYYYYYY1 & 0b00000001 =1, where Y is a don't care bit
if bit 0 is low:
0bYYYYYYY0 & 0b00000001 = 0
Continue with right hand side marching a 1 across to test all the bits.
Another example:
if bit 3 is high:
0bYYYY1YYY & 0b00001000 = 0b00001000, or !0, where Y is a don't care bit
if bit 3 is low:
0bYYYY0YYY & 0b00001000 = 0
I have used this technique successfully before, looking for a 0, or a Not 0, so the actual value does not matter.