Thread: Right Shifting

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2002
    Location
    Hyderabad
    Posts
    17
    Rep Power
    0

    Right Shifting


    Hai All,

    Here is a some code i executed , its giving some what strange values , right shift means dividing the value by 2 . On this basis i have excuted the code.

    The code follows

    #include <stdio.h>

    int main()
    {
    char ch = -0x7f ;
    int i = ch;
    printf("%d %d %d %d\n",ch,ch>>1,-127/2,i/2);
    }

    Out put is :

    -127 -64 -63 -63

    Here -127/2 and i/2 are giving -63 as a result
    But ch>>1 is giving -64 as a result . How it is possible ?

    Please explain me.

    Suri
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,648
    Rep Power
    4248
    -0x7f is 1111111110000001 in binary (assuming a 16 bit variable). Right shifting this by one bit gives us 1111111110000000 which translates to 64 in decimal. Now -127/2 is -63.5 actually. However, when C performs integer divisions (i.e. both numerator and denominator are integers), it always truncates the value. Hence 63.5 will be truncated to 63.

IMN logo majestic logo threadwatch logo seochat tools logo