0

Can't understand behavior of this bit shift:

int container = 1;

cout<<(container>>32)<<endl;

If it's logical shift the output should be 0, but it's 1 instead, as if it was cyclic shift. When looking at disassembly I see that command used is SAR. Please explain this behavior to me.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
goodking
  • 145
  • 1
  • 12
  • 2
    http://stackoverflow.com/questions/18918256/is-right-shift-undefined-behavior-if-the-count-is-larger-than-the-width-of-the-t – Commander Coriander Salamander Aug 03 '15 at 18:56
  • Your compiler should have warned you about this. Did you try the `-Wall` option? – 5gon12eder Aug 03 '15 at 18:57
  • Visual Studio produces a warning. On X86 / X64, the 32 bit operand shift instructions only use the bottom 5 bits of the count, in this case: 32&0x1f == 0. You could have used container >>= 31; container >>= 1; and that would work (should produce 0 or -1 on X86 / X64). – rcgldr Aug 03 '15 at 23:28

1 Answers1

0

You shifted a 32-bit number by 32, which results in undefined behavior, and the resulting 1 is a coincidence.

Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55
  • Yes it's undefined behavoir. But I tried it with different values, on different compilers and it's allways the same. – goodking Aug 03 '15 at 19:34
  • And that means it's not undefined behaviour because ...? I would try it on a different architecture and see what happens. – john Aug 03 '15 at 20:36
  • I don't say it's not undefined behaviour. I'm just trying to understand why it happens like that. – goodking Aug 04 '15 at 07:28
  • The compiler tries by remainder (reminder on the division of number-of-shifts per length-of-operand) if the number of shifts is greater than operand length – Rassoul Apr 16 '18 at 06:56
  • https://stackoverflow.com/questions/49826523/undoing-shifts-without-truncating/49826656#49826656 – Rassoul Apr 16 '18 at 10:10