EmbLogic's Blog

query regarding bit shift operations

#include<stdio.h>
int main()
{
int i=255;
i=i<<24;
i=i>>24;
printf(“%d”,i);
return 0;
}

output is : -1

how??

3 Responses to query regarding bit shift operations

  1. u have taken int and it is four byte long take it as char then check the output.

  2. ashish.dahiya says:

    hi,,,
    we have i=255;
    its bit pattern is
    00000000 00000000 00000000 11111111
    now applying only i<<24
    00000000 00000000 11111111 00000000 (8) shift
    00000000 11111111 00000000 00000000 (16) shift
    11111111 00000000 00000000 00000000 (24) shift
    now i=i<>24
    in right shifting (we follow arithmetic shifting) in which if the leftmost bit is 1 then we will fill it with 0 .if leftmost bit is 1 then it is filled with 1;(this is exception in right shift while there is not such exception in left shifting).
    on first 8bit right shifting we get
    11111111 11111111 00000000 00000000
    on 16 bit shifting we get
    11111111 11111111 11111111 00000000
    on 24 bit shifting
    11111111 11111111 1111111 11111111
    after shifting this is assigned to i
    i=i>>24;
    so i becomes
    i=11111111 11111111 1111111 11111111
    and in decimal form this is (-1).

Leave a Reply to saurabh.gulia Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>