Re: gcc and bitwise right shift
Re: gcc and bitwise right shift
- Subject: Re: gcc and bitwise right shift
- From: John Engelhart <email@hidden>
- Date: Wed, 18 Mar 2009 10:32:57 -0400
On Wed, Mar 18, 2009 at 7:14 AM, Jeremy Pereira <email@hidden> wrote:
>
> On 17 Mar 2009, at 19:09, Thierry Faucounau wrote:
>
>> As far as I understood it, bitwise shifts using << or >> in C were logical
>> shifts (ie. bringing in zeros). However, I just hit a difference in behavior
>> between the windows compiler and gcc and I haev to say, I sort of side with
>> VC++ on this one.
>
> This is beside the main point, but your understanding is incorrect. The C
> compiler uses an arithmetic shift for right shifts which means the sign is
> preserved. e.g.
Quoth the C99 standard
(http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf):
6.5.7 Bitwise shift operators
point 4: The result of E1 << E2 is E1 left-shifted E2 bit positions;
vacated bits are filled with zeros. If E1 has an unsigned type, the
value of the result is E1 * 2^E2, reduced modulo one more than the
maximum value representable in the result type. If E1 has a signed
type and nonnegative value, and E1 * 2^E2 is representable in the
result type, then that is the resulting value; otherwise, the behavior
is undefined.
point 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 / 2^E2. If E1 has a signed type and a negative value,
the resulting value is implementation-defined.
So, no, the standard does not mandate arithmetic right shifts (i.e., a
signed type with a negative value has its vacated bits filled with
ones, preserving the sign of the value).
GCC's 'C Implementation-defined Behavior' section
(http://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Integers-implementation.html#Integers-implementation):
o The results of some bitwise operations on signed integers (C90 6.3, C99 6.5).
Bitwise operators act on the representation of the value including
both the sign and value bits, where the sign bit is considered
immediately above the highest-value value bit. Signed `>>' acts on
negative numbers by sign extension.
GCC does not use the latitude given in C99 only to treat certain
aspects of signed `<<' as undefined, but this is subject to change.
So, GCC implements right shifts of signed types as 'arithmetic
shifts', preserving the sign of the shifted value.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden