Re: Evaluate 16-bit signed value 0x8000 after left shift by 2

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On fre, 2014-06-13 at 06:42 +0000, Sandeep Kumar Singh wrote:
> Hi,
> 
> I need some help/clarification,
> I am expecting zero value of 16-bit signed value 0x8000 after left shift by 2
> Below is my test case.
> 
> Test case:
> ========
> int main()
> {
> 	register signed short val1 = 0x8000 ;
> 	signed short val2 ;
> 	val2 = ( ( val1 << 2 ) >> 2 ) ;              /* val2 should be 0. */
> 	printf( "\nval2 is :%x\n", val2 ) ;    /* But Val2 is ffff8000 */
> 	return 0 ;
> }
> 
> Steps to reproduce:
> $gcc   test.c
> $run   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).
> 
> Best Regards,
> Sandeep Kumar Singh
> 
> 
I'm a bit rusty on how C does things but:

if I run your example and replaces %x in the printf with %hx my computer
prints "8000" which is somewhat logical since h asks printf to consider
the variable to be a short int and not a regular int.

The other thing could be that the architecture is 32 bit and the
operations are made on 32 bit words. so you'r short is represented as

	0xffff8000 in memory and then the value is shifted and left to
	0xff800000 the next right shift just moves it back
	0xffff8000

I believe the returning f could be a cpu feature that automatically adds
ones where bits would be unknown.

Regards
/Åke





[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux