#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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With