BITWISE OPERATORS IN CPP

0
34

INTRODUCTION

In programming, a bitwise operation operates on one or more binary representations of numbers.It is fast and simple proceduOn simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplicationre, and is used to manipulate values for comparisons and calculations.

Different Bitwise operators

  • Left shift: [variable]<<[number of places to shift the bits] – equivalent to integer multiplication by a power of 2
  • Right shift: [variable]>>[number of places to shift the bits] – equivalent to integer division by a power of 2
  • Bitwise AND: &
  • Bitwise OR: |
  • Bitwise XOR: ^
  • Bitwise complement: ~
  • Bitwise OR is commutative
  • Bitwise XOR is commutative, also 0^x = x and x^x = 0 are two very useful identities

Coding problems related to bitwise operators in cpp

Problem Statement:

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

while(Dividend >= Divisor)
 {
long temp = Divisor, count = 1;
	while(temp <= Dividend)
	{
           	 	temp <<= 1;
            		count <<= 1;
    	}
	result = result + (count >> 1);
	Dividend = dividend – (temp >> 1);
}

EXPLANATION

Check if Dividend is greater than or equal to Divisor

We left shift the divisor and check if the result is less than the dividend. If less left shift a counter. Store the result in a temp variable.

Again left shift the above result and the counter. Check again if the result is less than the dividend. If less, then continue with this step.

If the result is greater than the dividend, then we right-shift both the counter and temp variable and save the new counter value in the final result. And we decrement the dividend with the new value of temp.

PROBLEM STATEMENT

Perform multiplication operation using Bitwise operators.Multiply a number with 2 ^n

void multiply_2_n(int num, int n)
{
	cout<<"The number "<<num<< " raised to 2 power of "<<n<<" is = "<< (num <<n)<<endl;

}

We know the left shift operator is a 2 raised to the power of n.
Hence we do num << n, should give us the expected result.

FAQ’S

Detect if two integers have opposite signs?

The two integers have the different signs if their MSB (bit) is different. In “C” Language using the EX-OR operator, we can check the sign of the integers.

How to set a particular bit in C?

Bitwise OR operator (|) use to set a bit of integral data type.”OR” of two bits is always one if any one of them is one.

How to check if a particular bit is set in C?

To check the nth bit, shift the ‘1’ nth position toward the left and then “AND” it with the number.