Tuesday, October 6, 2015

C language : bitwise operator



This post is more like patchwork.

Even though most of the things has been covered, but still we can have some questions  about known things, which if not working regularly can put us in doubt.

1) Right Shift on Signed type

int a= 0x80;

a= a>>1;

// Main thing is what will happen to MSB , will it be substituted by 0 or 1.

The sign bit on right shift retains it original value , so if it was 0 , it will remain so. If it was 1 , it will remain so. 

int  a=-0x80;

a = a>>1;

2) Right Shift on Unsigned type


The MSB will be replaced by 0.

3) Left Shift on Signed Type or unsigned type

It doesn't have any effect.  Only thing to note is if for SIGNED MSB becomes 1 due to left shift, then while printing its value we should not be surprised by its negative value.


Difference between + and &. 

+ is same as &, only thing is in case of + , we carry forward .

Ex :  0011 + 0010  , in this case when we came to 2nd LSB 1+1 will give as 0 and we will carry forward the 1, In case of & NO.


While making program, I am bit surprised to see one thing.

Try to run below program and see if you can get it.

unsigned int a= -0x80;

printf("%d",a);

a = a<<1;

printf("%d",a);


When you will run this program, you will notice NEGATIVE value. But a is UNSIGNED then WHY ??


It is due to %d argument,   In C , SIGNED is default. Same was %d is for signed int, but we are accustomed to us it everywhere.

The correct format type is %u. 

No comments:

Post a Comment