Bitwise-AND

You can also bitwise-AND two bytes together to create a third. In this case, a bit on the third byte is 1 if the corresponding bits in the first two bytes are both 1.

Figure 33.4  Two bytes bitwise-ANDed together

Two bytes bitwise-ANDed together

This is done with the & operator. Add the following lines to main.c:

#​i​n​c​l​u​d​e​ ​<​s​t​d​i​o​.​h​>​

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​u​n​s​i​g​n​e​d​ ​c​h​a​r​ ​a​ ​=​ ​0​x​3​c​;​
 ​ ​ ​ ​u​n​s​i​g​n​e​d​ ​c​h​a​r​ ​b​ ​=​ ​0​x​a​9​;​
 ​ ​ ​ ​u​n​s​i​g​n​e​d​ ​c​h​a​r​ ​c​ ​=​ ​a​ ​|​ ​b​;​

 ​ ​ ​ ​p​r​i​n​t​f​(​"​H​e​x​:​ ​%​x​ ​|​ ​%​x​ ​=​ ​%​x​​n​"​,​ ​a​,​ ​b​,​ ​c​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​D​e​c​i​m​a​l​:​ ​%​d​ ​|​ ​%​d​ ​=​ ​%​d​​n​"​,​ ​a​,​ ​b​,​ ​c​)​;​

 ​ ​ ​ ​u​n​s​i​g​n​e​d​ ​c​h​a​r​ ​d​ ​=​ ​a​ ​&​ ​b​;​

 ​ ​ ​ ​p​r​i​n​t​f​(​"​H​e​x​:​ ​%​x​ ​&​ ​%​x​ ​=​ ​%​x​​n​"​,​ ​a​,​ ​b​,​ ​d​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​D​e​c​i​m​a​l​:​ ​%​d​ ​&​ ​%​d​ ​=​ ​%​d​​n​"​,​ ​a​,​ ​b​,​ ​d​)​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

When you run it, you will see the two bytes bitwise-ANDed together:

H​e​x​:​ ​3​c​ ​&​ ​a​9​ ​=​ ​2​8​
D​e​c​i​m​a​l​:​ ​6​0​ ​&​ ​1​6​9​ ​=​ ​4​0​

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:

i​f​ ​(​[​c​u​r​r​e​n​t​D​e​t​e​c​t​o​r​ ​c​h​e​c​k​i​n​g​T​y​p​e​s​]​ ​&​ ​N​S​T​e​x​t​C​h​e​c​k​i​n​g​T​y​p​e​P​h​o​n​e​N​u​m​b​e​r​)​ ​{​
 ​ ​ ​ ​N​S​L​o​g​(​@​"​T​h​i​s​ ​o​n​e​ ​i​s​ ​l​o​o​k​i​n​g​ ​f​o​r​ ​p​h​o​n​e​ ​n​u​m​b​e​r​s​"​)​;​
}​

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’ll get a non-zero result, and you’ll know that this data detector does look for phone numbers.

Note that when we use bits this way, we don’t care what the integers in these cases equate to numerically. We use the bit placement within the integer to represent something other than a certain power of 2.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset