You can also bitwise-AND two bytes together to create a third. In this case, a bit on the third byte is 1 only if the corresponding bits in the first two bytes are both 1.
This is done with the & operator. Add the following lines to main.c:
#include <stdio.h> int main (int argc, const char * argv[]) { unsigned char a = 0x3c; unsigned char b = 0xa9; unsigned char c = a | b; printf("Hex: %x | %x = %xn", a, b, c); printf("Decimal: %d | %d = %dn", a, b, c); unsigned char d = a & b; printf("Hex: %x & %x = %xn", a, b, d); printf("Decimal: %d & %d = %dn", a, b, d); return 0; }
When you run it, you will see the two bytes bitwise-ANDed together:
Hex: 3c & a9 = 28 Decimal: 60 & 169 = 40
In Objective-C, we use bitwise-AND to see if a certain bit, or flag, is on. For example, if you were handed an instance of NSDataDetector, you could check if it was set to look for phone numbers like this:
if ([currentDetector checkingTypes] & NSTextCheckingTypePhoneNumber) { NSLog(@"This one is looking for phone numbers"); }
The checkingTypes method returns an integer that is the bitwise-OR result of all the flags this instance of NSDataDetector has on. You bitwise-AND this integer with a particular NSTextCheckingType constant and check the result. If the bit that is on in NSTextCheckingTypePhoneNumber is not on in the data detector’s setting, then the result of bitwise-ANDing them will be all zeroes. Otherwise, you will get a non-zero result, and you will know that this data detector does look for phone numbers.
Note that when we use bits this way, we do not care what the integers in these cases equate to numerically.