Shifting Bits

You can take the 8 bits of a byte and shift them all to the left or to the right. You can do this using the bitwise left shift operator (<<) or the bitwise right shift operator (>>). Notice in Figure 7.8 how each shift is in its own box. You are essentially moving a bit to the next box over.

Image

Figure 7.8 Shifting bits to the left.

You could write this in code like so:

var a:UInt8 = 0b01010101 //85a << 1 //170

Notice that this bitwise left shift had the effect of doubling the integer. Doing a bitwise right shift, on the other hand, halves the number:

var a:UInt8 = 0b01010101 //85a >> 1 //42

Notice that because you are working with ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.