Jeffrey Lebowski
Jeffrey Lebowski

Reputation: 75

Arithmetic Right Shift in C

In C, on a 32-bit machine, I was just wondering if 1>>31 returns -1 given 1 is a signed integer, since for 2's-complement, while doing right shift (arithmetic), sign bit is copied giving the result

1111 1111 1111 1111 1111 1111 1111 1111

Upvotes: 0

Views: 863

Answers (4)

tf3
tf3

Reputation: 467

The following code helps determine whether the right shift is arithmetic for signed integers, for an implementation which uses two's complement representation for ints.

#include <stdio.h>

//below function returns 1 if system is little endian, 0 otherwise
int is_little_endian() { //checks endianness
  short x = 0x0100; //256
  char *p = (char*) &x;
  if (p[0] == 0) {
    return 1; 
  }
  return 0;
}

/* Below function returns 1 if shifts are arithmetic, 0 otherwise.
   It checks whether the most significant bit is 1 or 0, for an int which
   had most the significant bit as 1 prior to the right shift. If the MSB
   is 1 after the bit shift, then the (unsigned) value of the most
   significant Byte would be 255.
*/

int int_shifts_are_arithmetic() {
  int x = -2;
  x = x >> 1 ;
  char *px = (char*)&x;
  if (is_little_endian()) {
    unsigned char *upx = (unsigned char*)&px[(int)sizeof(int) - 1];
    if (upx[0] == 255) return 1; 
    return 0;
  } else { //big endian
    unsigned char* upx = (unsigned char*)px;
    if (upx[0] == 255) return 1;
    return 0;
  }
}

int main() {
  if (int_shifts_are_arithmetic()) {
    printf("Shifts are arithmetic\n");
  }
  else {
    printf("Shifts are not arithmetic\n");
  }
  return 0;
}

Upvotes: 0

Richard Schneider
Richard Schneider

Reputation: 35464

The result of 1>>31 is zero because the sign bit of 1 is 0.

However, you can not count on the sign bit being replicated, because according to K&R Second edition the results are implementation-defined for right-shifts of signed values.

Upvotes: 0

The result will be zero because the the sign bit (most significant bit) is 0 for the integer 1:

0000 0000 0000 0000 0000 0000 0000 0001
^

Upvotes: 2

Jon
Jon

Reputation: 437904

No, the result will be zero in any conforming implementation.

C99, 6.5.7/5 ("Bitwise shift operators") states:

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 / 2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Since 1 is nonnegative, the result is the integral quotient of 1 / (2^31) which is obviously zero.

Upvotes: 2

Related Questions