Getting Started

(lily) #1

Chapter 4: C Types, Operators, and Expressions


r maybe myByte = 0x55:

yByte = 0xAA:

he above cases we are only dealing with a single bit, but we might be

. Let’s set bit 6,
gardl regardless of their
esent as they were when


hich does the following:

AND = 00001000


O


myByte = 01010101 = 0x55
0x08 = 00001000 = 0x08


AND = 00000000 = 0x00


And maybe m


myByte = 10101011 = 0xAA
0x08 = 00001000 = 0x08


AND = 00001000 = 0x08


In each of t
interested in any or all of the bits. One of the most important features of using
masks with bitwise operators is that it allows us to set or clear a specific bit or set
of bits in a byte without knowing or affecting the bits we aren’t interested in. For
example, suppose we are only interested in bits 0, 2, and 6
re ess of its present value, then clear bits 0 and 2, also
pr value and, here’s the trick, leave bits 1, 2, 4, 5, and 7
we began. Let’s have myByte starting equal to the secret to life the universe and
everything, which according to Douglas Adams is 42, but remember that the start
value doesn’t matter to us since we are going to force 3 bits to values regardless
of the start value.


NOTE:
myByte = myByte | 0x08;
is the same as
myByte |= 0x08;
which we will use from no on.


At the beginning myByte is equal to 42 = 0x2B = 00101011. We set bit 6 with:


myByte |= 0x40;


w

Free download pdf