1

I am running GDB through a snippet of code which is doing a left shift of 1 by 10000.

Here is the code

uint32_t x = (1 << y ) 

The value of y is 10000.

I was expecting a value of 0 for x, but I see that x has a value of 65536. Quite strange.

GDb also shows this behavior

(gdb) p 1<<10000
$52 = 65536
(gdb) p 1<<9984
$54 = 1

What's wrong with this?

Jongware
  • 22,200
  • 8
  • 54
  • 100
kumar
  • 2,696
  • 3
  • 26
  • 34
  • 8
    It is undefined behavior to [shift by the bit length of a variable or greater](http://stackoverflow.com/q/21894503/1708801) – Shafik Yaghmour Mar 12 '15 at 18:17
  • 3
    If X doesn't work as expected, most likely it's your expectations that need fixing. – Kerrek SB Mar 12 '15 at 18:20
  • if my memory is correct, gcc will wrap over the number into the valid zone, i,e, `1<<10000 == 1 << (10000 % (8 * sizeof(uint32_t)))`. – Jason Hu Mar 12 '15 at 18:26
  • @haccks I really dislike cross tag duplicates, we can't find a highly upvoted C version? – Shafik Yaghmour Mar 12 '15 at 18:39
  • It reminds me of TI C6000 that can do bitshift using either shifter or multiplier. Shifter version wraps right hand into 0-31 while the multiplier version saturates right hand to -31 or +31 and used sign to determine directionality. – user3528438 Mar 12 '15 at 19:03

0 Answers0