X86_64 bit shifts

Michael Meissner michael.meissner@amd.com
Fri Jul 6 15:27:00 GMT 2007


On Fri, Jul 06, 2007 at 06:06:43AM -0600, Wachdorf, Daniel R wrote:
> I am seeing an odd behavior and was wondering if it was a bug.  In
> X86_64, Gcc is sign extending a bit shift operation when assigned to an
> unsigned long.  Specifically:
> 
> #include <stdio.h>
> 
> int main(){
> 
>     unsigned long val;
> 
>     val = (1 << 31);
> 
>     printf("Val = %lx\n", val);
> 
>     return 0;
> }
> 
> This results in:
> 
> Val = 0xffffffff80000000;
> 
> Should the result be 0x80000000?  I understand that the bit shift is a
> 32 bit operation, but shouldn't the compiler then up convert that to a
> 64 bit unsigned long?

'1' has signed int type (which on x86_64 is 32-bits), so (1 << 31) is a signed
int type and is negative.  If you use 1LU instead of 1, then it is an unsigned
64-bit type, and does not suffer from sign extension:

	val = (1LU << 31);

-- 
Michael Meissner, AMD
90 Central Street, MS 83-29, Boxborough, MA, 01719, USA
michael.meissner@amd.com




More information about the Gcc mailing list