How to perform the bitwise NOT operation in Swift

The bitwise NOT operator flips all the bits in an 8-bit number. Hence, 0 becomes 1, and 1 becomes 0. It is represented by the tilde symbol (~).

Note: For binary representations of integers where the number of bits are less than 8, we add extra 0's to the left such that the number of bits equal a multiple of 8.

Syntax

~NUM

Parameters

Bitwise NOT is a prefix operator and appears immediately before any NUM.

Return value

The bitwise NOT operator returns 1 when the bit is 0, and 0 when the bit is 1. In other words, for any integer nn, it returns (n+1)-(n+1). The possible return values of ~ on different bits are summarized below:

Possible return values of the NOT operator

NUM

~NUM

1

0

0

1

Code

The code that defines the NOT operator is as follows:

// declare an integer variable
var number = 10 // binary: 00001010
// perform bitwise NOT operation
var resultNumber = ~number
print(resultNumber) // -11 , binary: 11110101
// The answer is supported by the following
// calculation as well:
// -(10+1) = -11

Explanation

The explanation of the above code is as follows:

  • Line 2: We declare a variable, number, and assign it the integer value 10 (00001010 in binary).
  • Line 5: We perform the bitwise NOT operation. The integer number is traversed bitwise, and the resulting bit is set to 1 if the bit is 0. Otherwise, it is set to 0. We store the final answer in the resultNumber variable. The complete calculation is shown below:
Bitwise NOT operation on an integer (10)

To convert a binary into a negative decimal, the left-most bit represents the sign (negative if 1 and positive if 0). In the example above, the left-most bit is 1 so the answer is a negative value. The calculation is shown below:

resultNumber=(127)+(126)+(125)+(124)+(023)+(122)+(021)+(120)=128+117=11 resultNumber=(-1*2^7)+(1*2^6)+(1*2^5)+(1*2^4)+(0*2^3)+(1*2^2)+(0*2^1)+(1*2^0) = -128+117 = -11

Copyright ©2024 Educative, Inc. All rights reserved