comp.lang.c
[Top] [All Lists]

Re: Strange bit shifting result with gcc - am I missing something obvio

Subject: Re: Strange bit shifting result with gcc - am I missing something obvious?
From: "Bartc"
Date: Sun, 30 Mar 2008 21:20:59 GMT
Newsgroups: comp.lang.c


"jacob navia" <jacob@xxxxxxxxxx> wrote in message 
news:fsotm8$kpc$1@xxxxxxxxxxx
> Boltar wrote:
>> On 32 bit linux with gcc 4.2 I get unexpected results with this code:
>>
>> main()
>> {
>>         int bits = 32;
>>         printf("%d\n",(int)1 << (int)32);
>>         printf("%d\n",(int)1 << bits);
>> }
>>
>>
>> The first printf gives a result of 0, the second gives 1. I checked
>> with sizeof() and ints are definately 32 bits in size.
>>
>> I'm sure I'm missing something obvious but can someone tell me what?

> When I compile tyour code with lcc-win I get:

> Warning tshift.c: 5  shift by 32 is undefined
>
> The number of bits shifted is greater than sizeof(int)*CHAR_BIT
> This is undefined!

OK, but the following code from lccwin does not appear to set up the shift 
count in cl register. So you don't even attempt to shift by 32, but by an 
unknown value in cl (presumably 24)?

;    6         printf("%d\n",(int)1 << (int)32);
        .line   6
        movl    $1,%edi
        movl    $32,%esi
        sall    %cl,%edi

On the x86 at least, shifting a 32-bit register left by 32 is anyway a 
no-operation (the register is unchanged).

So the OP should not rely on 32+ bit left-shifts working as he expects.

-- 
Bart




<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy