Sometimes you want to send a binary value into Processing (say, from a microcontroller) and check the individual bits of the value. This example checks the bits of an 8-bit number individually, and reports whether each one is a 0 or a 1.
/*
Checking a number's bits with a bitmask
by Tom Igoe
Checks the bits of a number one at a time using the shift (<<)
and bitwise AND (&) functions.
Updated 6 December 2005
*/
// get a random number between 0 and 255, convert to a byte:
byte someNumber = (byte)random(255);
// loop over the number one bit at a time:
for (int i = 0; i <= 7; i++) {
//print the number as an 8-bit binary number:
println("someNumber = " + binary(someNumber, 8));
// print the bitmask as an 8-bit binary number:
byte bitmask = (byte)(1<<i);
println("bitmask = " + binary(bitmask, 8));
// if the number has the bit in the bitmask set to 1, then say so:
if ((someNumber & bitmask) == bitmask) {
println("bit " + i + " = 1");
}
else {
println("bit " + i + " = 0");
}
// print a couple of linefeeds for clean printing:
println("\n\n");
}