0

I looked at the binary representations of negative integers under the influence of the bit-shift and I noticed that bitshifting behaves differently for these than for positive ones.

int imax = std::numeric_limits<int>::max();

std::bitset<32> bs0(imax+1);

std::cout << bs0 << "\n";

std::bitset<32> bs1((imax+1) >> 1);

std::cout << bs1 << "\n";

std::bitset<32> bs2((imax+1) >> 2);

std::cout << bs2 << "\n";

Output:

10000000000000000000000000000000
11000000000000000000000000000000
11100000000000000000000000000000

What I had expected was:

10000000000000000000000000000000
01000000000000000000000000000000
00100000000000000000000000000000

What is this behaviour for? Or - if there is no reason per se for it - then why does it happen?

lo tolmencre
  • 3,804
  • 3
  • 30
  • 60
  • Shifting right for a signed value (usually) propagates the sign bit. If you don't want to propagate the sign bit, use an unsigned value. – clstrfsck Aug 23 '16 at 23:15
  • " For negative a, the value of a >> b is implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative)." source: http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_shift_operators implementation-defined means look at your implementation's docs. – Richard Critten Aug 23 '16 at 23:16
  • 1
    And many many more easily found via *"site:stackoverflow.com c++ right-shift of negative numbers"* in your favorite search engine. – Baum mit Augen Aug 23 '16 at 23:16

0 Answers0