0

how do I perform a signed right shift in c? like -25 >> 3.

I tried like this: 10011001 >> 3 == 00010011

But the result is -4.

Waqas Shabbir
  • 755
  • 1
  • 14
  • 34
chen
  • 3
  • 1

3 Answers3

3

According to the standard 6.5.7p5

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 /2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

The result is implementation-defined, and you should look up how it is defined there.

Assuming twos complement and signed right shift, -25 is 11100111, shifting it by 3 will lead to 11111100 which is -4.

Osiris
  • 2,783
  • 9
  • 17
0

That is a signed right shift. In signed shifting, a negative number (identified by the '1' in the highest bit) is often filled from the left. (Although this depends on the specific compiler. It looks like this is what your compiler is doing.) 11100111 --> 11110011 --> 11111001 --> 11111100

What it sounds like you're looking for is an unsigned shift. If you use (signed char)(((unsigned char)-25)>>3) you probably will get the results you're looking for.

jwismar
  • 12,164
  • 3
  • 32
  • 44
0

As the right shift of the signed integer is implementation defined from my experience the result depends on the availability of the arithmetic shift on the target machine. Because nowadays is rather hard to find any computers or uC without it is almost always the result of the arithmetic shift right

From Wikipedia: enter image description here

0___________
  • 60,014
  • 4
  • 34
  • 74