ProAnswers.org

What is equivalent of multiplying an unsigned int by 2: left shift of number by 1 or right shift of number by 1 in C?

Left shifting of an unsigned integer is equivalent to multiplying an unsigned int by 2.

Eg1: 14<<1;

Consider a number 14-----00001110 (8+4+2)is its binary equivalent

left shift it by 1--------------00011100(16+8+4) which is 28.

Eg2: 1<<1;

consider the number as 1—00000001(0+0+1).

left shift that by 1------------00000010(0+2+0) which is 2.

left shift by 1 bit of a number=2*number

left shift by 1 bit of 2number=22*number

left shift by n bits of number=(2^n)*number

Program: Program to illustrate left shift and right shift operations.

#include

int main(void)

{

int x=10,y=10;

printf("left shift of 10 is %d
",x<<1);

printf("right shift of 10 is %d
",y>>1);

return 0;

}

Output:

left shift of 10 is 20

right shift of 10 is 5

Explanation:

Left shift (by 1 position) multiplies a number by two. Right shift divides a number by 2.