top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Evaluate 16-bit signed value after left shift by 2

+3 votes
349 views

I am expecting zero value of 16-bit signed value 0x8000 after left shift by 2.

Following is my code

int main()
{
 register signed short val1 = 0x8000 ;
 signed short val2 ;
 val2 = ( ( val1 > 2 ) ; /* val2 should be 0. */
 printf( "nval2 is :%xn", val2 ) ; /* But Val2 is ffff8000 */
 return 0 ;
}

$ gcc myfile.c
$ ./a.out

I have verified the same behavior with 32-bit compilers and expected (val2=0) with 16-bit compiler. I can correct this by shifting 18 in place of 2 as a workaround. I want some verify my understanding for this point and another way to get expected result (if any).

posted Jun 13, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

signed short is 2 bytes(16 bits) long and it ranges from -32768 to +32767.
When you store 0x8000 in val1 ( SIGNED SHORT), it is actually considered a s a negative number because the sign bit is set high.
Binary representation - 1000 0000 0000 0000 for 0x8000.

You can verify it by printing the value of val1 as "%d" immediately after storing 0x8000 in it. It will print -32768.
So in 0xffff8000, FFFF indicates that it is a negaive number and 8000 is the value.
Similarly if you right shift this number by 2, the next 2 bits will be set high because of the signed bit copy mechanism. So val1 >>2 will give 0xFFFFe000 where FFFF signifies it is a negative number.
And 0x8000 -> 1000 0000 0000 0000 becomes 0xE000 -> 1110 0000 0000 0000 .

For more info you can follow this link
http://stackoverflow.com/questions/1857928/right-shifting-negative-numbers-in-c

Hope this helps.

answer Jun 13, 2014 by Ankush Surelia
0 votes

Read this article which I wrote long back
http://tech.queryhome.com/45054/bitwise-shift-and-negative-numbers-in-c-c

When we right-shift then the filling is done as 0 if most significant bit is 0, one if most significant bit is one. Here the most significant bit is one so filling is done as one.

answer Jun 13, 2014 by Salil Agrawal
Similar Questions
+2 votes

In a 32 bit only one bit is on, with out using loops, goto, or recursion how to find out which position is on?
example : 4 ---> 2nd bit ( 0000 0100)

+8 votes

For example, 00000001 11001100 becomes 11001100 00000001;

unsigned short swap_bytes(unsigned short x) {

}

...