English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Bitwise and Shift Operators

In this tutorial, you will learn about different bit operations in Swift. They are used for bitwise calculations in expressions.

Bits are used to represent binary numbers. A binary number can have two possible values, 0 or1.As a beginner programmer, you do not need to use operations at the bit level.

Using primitive data types, such as: integer, float, boolean, string, etc., is sufficient. When dealing with low-level programming, you may need to work at the bit level.

In addition toBasic operationsIn addition, Swift also provides a set of rich operators to operate on bits. These operators are similar to logical operators, but they handle the binary representation of data (bits).

Bitwise operators are used to change the bits of the operands. The operands are the variables or constants in which the operations are performed.

The following lists all the bitwise operators available in Swift:

1.Bitwise NOT operator

It is represented by the tilde ~ and can be applied to a single operand. This will reverse all bits. That is, it will1Change it to 0, change 0 to1.

If x is a binary value (i.e., 0 or1)of the variable/If it is a constant, the bitwise NOT operation of the x variable can be represented in the table below:

Bitwise NOT operation
xto ~x
01
10

Example1: The bitwise NOT operator of unsigned integers

is8 = 1 
let invertedNumber = ~initalNumber 
print(invertedNumber)

When you run the above program, the output will be:

254

let initalNumber:UInt8 = 1 . In the above program, the statement let initalNumber:UInt8is of type Unsigned int, with a size of1bits. Therefore, the decimal1. It can be represented as 0000000

binary.1while1The bitwise NOT operator will change all bits of a variable or constant, changing bit 0 to11111110. It will change to 0. Therefore, the reversed number contains bits254. After converting it to decimal, it represents254.

. Therefore, the statement print(invertedNumber ) is output on the screen

Example2can also perform bitwise operations directly on bits, as shown below:

: The bitwise NOT operator on a bit unit8 = 0b11111111
let initialBits: UInt  
let invertedBits = ~initialBits

When you run the above program, the output will be:

0

print(invertedBits)11111111initialBits contains the binary value255which corresponds to decimal8. To represent a number in binary, we use 0b as a prefix in the text. If there is no 0b as a prefix, it will treat it as a regular integer and an overflow error will occur (UInt255can only store numbers from

between the numbers).1Because we used the bitwise NOT operator, all8are all changed to 0. Therefore, the constant reverseBits contains 00000000, which is equivalent to UInt

Example3: The bitwise NOT operator of signed integers

let initalNumber:Int = 1 
let invertedNumber = ~initalNumber 
print(invertedNumber)

When you run the above program, the output will be:

-2

In the above program, the decimal1can be represented in binary as 00000001. The bitwise NOT operator will change all bits of a variable or constant, changing bit 0 to1change1Change to 0. Therefore, reversing the digits includes bits11111110. This should be output on the screen254. Instead, it returns-2. Isn't that strange? Let's see how it happens below.

let initalNumber: Int = 1It is a signed int that can contain both positive and negative integers. That's why when we apply a bitwise NOT operator to a signed integer, the binary number returned may also represent a negative number.

How the compiler converts -2 Explain11111110 What is the binary form?

The compiler uses two's complement to represent integers. To obtain the negative sign of an integer's two's complement, you should first write the number in binary form, then invert the number, and finally add 1 to the result.

Find-2Steps to obtain the two's complement of a number in binary form:

  1. written in binary form:2: 00000010

  2. reverse the digits. 0 becomes1while1to 0:11111101

  3. add1: 11111110

This is what the compiler converts binary numbers into1111110interpreted as decimal.-2in a way. However, the compiler has a small issue that we have not noticed. It also infers the type of invertedNumber as Int8type.

To understand this, let's look at the following example:

print(Int8(bitPattern: 0b11111110))
print(0b11111110)

When you run the above program, the output will be:

-2
254

In the above example, the compiler only handles the signed8bit integer treats the binary number as decimal-2. Therefore, the statement print(Int8(bitPattern: 0b11111110)) is output on the screen-2.

but for sizes of32/64bits and can accommodate integer types with larger values, interpreting the value as254. Therefore, the statement prints 0b11111110) is output254.

2. Bitwise AND operator

It is represented by & and can be applied to two operands. The AND operator compares two bits, if both bits are1Then return1Otherwise, return 0.

If x and y are variables/Constants, which save binary values, that is, 0 or1. The bitwise AND operation on x and y can be represented by the following table:

Bitwise AND
xyx & y
000
010
111
100

Example5:Bitwise AND operation

let xBits = 0b10000011
let yBits = 0b11111111
let result = xBits & yBits
print("Binary:", String(result, radix: 2))
print(result)

When you run the above program, the output will be:

Binary: 10000011
131

In the above program, the statement let result = xBits & yBits combines the bits of two operands xBits and yBits. If both bits are1Then return1Otherwise, return 0.

String(value , radix: ) initializer is used to represent numbers in different numeral systems. If we provide the base value2. It converts numbers to the binary number system. Similarly, we can use16represents hexadecimal, using10represents decimal.

The statement print("Binary:",String(result, radix: 2)) is output on the screen Binary:10000011.10000011equal to decimal131, the statement print(result) outputs131.

3. Bitwise OR operator

It is represented by | and can be applied to two operands. If one or more inputs of the bitwise OR operator are1,then the two bits are compared and the result is generated1,otherwise 0.

If x and y are kept as binary values (i.e., 0 or1)of the variable/constant, the bitwise OR of x and y can be represented by the following table:

Bitwise OR
xyx | y
000
011
111
101

Example6:Bitwise OR operation

let xBits = 0b10000011
let yBits = 0b11111111
let result = xBits | yBits
print("Binary:", String(result, radix: 2))
print(result)

When you run the above program, the output will be:

Binary: 11111111
255

In the above program, the statement let result = xBits | yBits combines the bits of two constants xBits and yBits. If any bit is1Then return1Otherwise, return 0.

The statement print("Binary:", String(result, radix: 2)) on the screenBinary:11111111. Because11111111with255decimal equivalent, so the print(result) statement outputs255.

4. Bitwise XOR operator

It is represented by ^ and can be applied to two operands. The XOR operator compares the bits, if only one of the inputs is1, then the result is generated.1Otherwise, return 0.

If x and y are variables/Constants, which save binary values, that is, 0 or1. The bitwise XOR operation on the bits of x and y can be represented by the following table:

XOR operation
xyx ^ y
000
011
110
101

Example7: Bitwise XOR operation

let xBits = 0b10000011
let yBits = 0b11111111
let result = xBits ^ yBits
print("Binary:", String(result, radix: 2))
print(result)

When you run the above program, the output will be:

Binary: 1111100
124

In the above program, the statement let result = xBits ^ yBits combines the bits of two constants xBits and yBits. If one of the bits is exactly1Then return1Otherwise, return 0.

The statement print("Binary:",String(result, radix: 2)) is output on the screenBinary:1111100(which is equivalent to 01111100). Because1111100 equivalent124In decimal, so the statement print(result) outputs124.

5. Bitwise shift operators

This operator is used to shift all bits in a number to the left or right by a certain number of positions and can be applied to a single operand. It is represented as << or >>.

There are two types of shift operators:

Bitwise left shift operator

  • Represented as <<

  • It will cause the bits to shift to the left, the shift being specified by the number followed by <<.

  • The vacated bit positions during the shift operation are filled with zeros.

  • Shifting the bits of an integer to the left doubles its value

Example8: Bitwise left shift operator

let someBits:UInt8 = 0b11000100
print(someBits << 1)

When you run the above program, the output will be:

136

In the above program, we used the left shift operator. Using <<1Representing shifting the bits to the left1. These numbers shift one position to the left, and the last digit on the right is filled with zero.

You can also see that the shifted digits from the left 'end' are lost. They will not come back from the right. Shifting it one position to the left will remove it from the binary1, and adds 0 to the right to fill the shifted value, while the rest of the bits shift to the left position1.

returns10001000, which is equivalent to UInt8in136. Therefore, print(someBits<<1) statement is output on the screen136.

Bitwise right shift operator

  • Represented as >>

  • It will cause the bits to shift to the right, followed by >>

  • For unsigned numbers, the vacated bit positions during the shift operation are filled with zeros.

  • For signed numbers (which can also be negative numbers), the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, then 0 is used; if the number is negative, then1.

  • Shifting one position to the right halves its value.

Example9The bitwise right shift operator for unsigned integers

let someBits: UInt8 = 4     
print(someBits >> 1)

When you run the above program, the output will be:

2

In the above program, we used the right shift operator for unsigned integers. Using >>1means moving the bits to the right1. The bits left by the shift operation are always filled with zeros for unsigned integers.

because4represented in binary as 00000100. Right shift one bit, return 00000010, which is equivalent to UInt8in2. Therefore, print(someBits>>1) statement is output on the screen2.

Example10: Bitwise right shift operator for signed integers

let someBits:Int = -4     
print(someBits >> 1)

When you run the above program, the output will be:

-2

In the above program, we used the right shift operator for unsigned integers. Unlike positive numbers, >> is used for negative numbers, and1filled in the empty spaces, rather than 0.

because-4represented in binary as11111100. Right shift one bit and move1filled in the empty spaces, and returns11111110, which is equivalent to Int8type-2. Therefore, print(someBits>>1)statement is output on the screen-2.