Basics of BIT Manipulation

Yasir
2 min readJan 18, 2021

--

Some basic things about BITs and its Manipulation

unDraw

To play with Bits , you must be familiar with binary numbers , and their operations like addition , subtraction etc .

Bit Operators

NOT ( ~ )

Bitwise NOT is an unary operator that flips the bits of the number i.e., if the ith bit is 0, it will change it to 1 and vice versa. Bitwise NOT is nothing but simply the one’s complement of a number. Lets take an example.

AND (&)

If both bits in the compared position of the bit patterns are 1, the bit in the resulting bit pattern is 1, otherwise 0.

01001011
00010101
--------
00000001

OR ( | )

If both bits in the compared position of the bit patterns are 0, the bit in the resulting bit pattern is 0, otherwise 1.

01001011
00010101
--------
01011111

XOR (^)

If both bits in the compared position of the bit patterns are 0 or 1, the bit in the resulting bit pattern is 0, otherwise 1.

01001011
00010101
--------
01011110

Left Shift ( << )

The bitwise left shift moves all bits in the number to the left and fills vacated bit positions with 0.

01001011
--------
00101100

Right Shift (>>)

Right shift operator is a binary operator which shift the some number of bits, in the given bit pattern, to the right and append 1 at the end.

Finding Even and Odd by BIT Manipulation

If a number is even , then there last bit is 0 , while if the number is odd then there last bit is 1 . So we will use and (&) operator to find the last digit , and if we got 1 then its odd and 0 then its even .

n = 8if n & 1 == 0:
print("Even")
else:
print("Odd")

Swap Two Values by BIT Manipulation

When you want to swap two values , you was doing this :

a = 10
b = 15
temp = a
a = b
b = temp

But now we will do the same thing with XOR operator . See the following approach :

a = 10
b = 20
a = a ^ b
b = a ^ b
a = a ^ b

Where to Go From Here

My GitHub: https://github.com/myawesomehub

My Writing : Link

Keep following to get more useful articles 👍
Mohamad Yasir
Thanks You !

--

--

Yasir
Yasir

Written by Yasir

Exploring Swift, SwiftUI, and Apple Universe.

No responses yet