Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right shift for signed integer

Tags:

c

#include<stdio.h>

int main()
{
  int num;

  printf("enter the number\n");
  scanf("%d",&num);

  int a,b;
  printf("enter the number of bits yiu want to shift\n");
  scanf("%d",&b);

  a=num>>b;

  printf("a is=%d\n",a);

  return 0;
}

Here for positive values of num, i get expected result.But with the negative values of num can,t find the answer giving a dry run of my programm. Just example consider i give num=-1 So -1 will be represented as 1111111111111111 and right shifting it by 1 should produce output 0111111111111111 that is 32767 in decimal form.But the output is -1.

like image 451
user2738777 Avatar asked Nov 30 '22 18:11

user2738777


1 Answers

From the C99 standard N1256 (emphasis mine):

6.5.7 Bitwise shift operators

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

like image 61
R Sahu Avatar answered Dec 15 '22 13:12

R Sahu