Help with shifting bits!

#include<stdio.h>
main()

{

int Oxygen=5;

printf("%d\n%d\n%d",Oxygen,Oxygen<<5,Oxygen>> 5);

return 0;

}

Result is 5
160
0

Couldnt understand the results..Please help
Your printf prints, Oxygen, then Oxygen shifted left 5 times, then Oxygen shifted right 5 times. Each of these shifts doesn't actually change what is stored in Oxygen, it just shows what the result of the operation is. That's why even after shifting left you don't get the original value when you shift right.

Assuming 32-bit integer
5 in binary
5 = 0000 0000 0000 0000 0000 0000 0000 0101

5 shifted left 5 times
5 << 5 = 0000 0000 0000 0000 0000 0000 1010 0000 = 160

5 shifted right 5 times (all the ones get shifted out leaving nothing but 0's)
5 >> 5 = 0000 0000 0000 0000 0000 0000 0000 0000 = 0
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
decimal    hex      binary
============================
   5        05      00000101
 160        A0      10100000
   0        00      00000000
   
   

   5        05      00000101
  10        0A      0000101.  // <- left shift 1
  20        14      000101..  // <- left shift 2
  40        28      00101...  // <- left shift 3
  80        50      0101....  // <- left shift 4
 160        A0      101.....  // <- left shift 5
 
 
   5        05      00000101
   2        02      .0000010  // <- right shift 1
   1        01      ..000001  // <- right shift 2
   0        00      ...00000  // <- right shift 3
   



EDIT: ninja'd
Last edited on
Thankyu both!! Got it now..
Topic archived. No new replies allowed.