BIT MANIPULATION

Before we talk about Bit Manipulation we shall understand the Binary Number system.

The Binary Number System is also known as base-2 number system. It is a procedure of representing numbers that counts by using combinations of only two numbers(one and zero) Basically computers use a binary number system to store and manipulate data.

Here the rightmost column represents one place and the second right column is two places and the thrid right column represents four places and four right columns represent 8 places and so on. You can observe we are using power of 2s. Two to the power of 0 is 1 and Two to the power of 2 is 4 and two to the power of 3 is 8 and so on. 

Now let’s write 5 in binary form 101. Here you can observe the rightmost “BIT” is 2 to the power of 0(1*20 )which is 1 right and the second rightmost bit is 0 which is (0*21) and 3 right most bit is 1 which is (1*24 ) if you add up to all you will get 5((1*20 )==1,(0*21) ==0,(1*23 )==4) all together makes 5. Now that’s the basics of the binary number system.

And let’s also talk about What is BIT??

The term bit is made of two words BInary and digiT. Bit is the smallest unit of memory or an instruction that a computer can store. The is 0 or 1.

Now, let’s talk about Bit Manipulation.

Bit Manipulation is all about manipulating data at the binary level. In normal number system we can manipulate number by using this operations(+,-,*,/,%, and etc…) To manipulate bits in binary level we also have some specific binary operators. Those are called BITWISE operators. There are a total six types of operators. 16 : Bitwise Operators (i) Bitwise operators cannot be applied to ...

Now one by one will cover these BITWISE operators.

BITWISE AND(&)

The AND operator is true when both bits are 1. The & (ampersand) is used for the AND operator.

aba&b
000
010
100
111

This bitwise operator “AND” works like this. For eg let’s take 2 binary form numbers 5 = (1,0,1) and 4=(1,0,0) and if we perform & operator between these two. The result will be 1,0,0 which is 4. 

BITWISE OR(|)

The bitwise or(|) operator works like. If you do “OR” of two bits. The result of OR is 1 if any of the two bits is 1.

aba|b
000
011
101
111

For eg: if you do 5(101)|6(110) the result will be 111which is 7

565|6 = 7
101
011
111

BITWISE XOR(^)

XOR means “exclusive or.” It evaluates to true only when one of the bits is 1. The ^ (caret) is used for the XOR operator. Basically the result of XOR is 1 if the two bits are different.

aba^b
000
110
101
011

For eg: if you do 5(101)^6(110) the result will be 011which is 3

565^6 = 3
110
011
101

BITWISE LEFTSHIFT(<<)

Leave a comment