As previously discussed, computer processors work in binary. These are essentially streams of ones and zeros with each one referred to as a bit. Bits are formed into groups of eight to form bytes. As such, it is not surprising that we, as programmers, will occasionally end up working at this level in our code. To facilitate this requirement, Swift provides a range of bit operators.

Those familiar with bitwise operators in other languages such as C, C++, C#, Objective-C, and Java will find nothing new in this area of the Swift language syntax. For those unfamiliar with binary numbers, now may be a good time to seek out reference materials on the subject to understand how ones and zeros are formed into bytes to form numbers. There are many authors who have done a much better job of describing the subject than we can do within the scope of this lesson.

For the purposes of this exercise, we will be working with the binary representation of two numbers (for the sake of brevity, we will be using 8-bit values in the following examples). First, the decimal number 171 is represented in binary as:

10101011

Second, the number 3 is represented by the following binary sequence:

00000011

Now that we have two binary numbers with which to work, we can begin to look at the Swift bitwise operators.

Get hands-on with 1200+ tech skills courses.