This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Peculiar behavior with bit-shifting
- From: Niklas Gürtler <profclonk at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Sun, 19 Feb 2017 16:58:48 +0100
- Subject: Re: Peculiar behavior with bit-shifting
- Authentication-results: sourceware.org; auth=none
- References: <fb1a7fa0-6f72-6615-35ab-2680467df4b6@pezley.net>
Your "id" variable is signed, and right-shifting signed integers yields
implementation-defined behaviour according to the C Standard, for
example copying instead of shifting the hightest (sign) bit. I'd suggest
that you do all bit-shifting and composing/decomposing on unsigned
integers, and cast input/output operands.
On 19.02.2017 16:44, Chris Pezley wrote:
> I've encountered a rather peculiar behavior in gcc (see below) and I'm
> unsure where to inquire about this. Would this be the correct place?
>
> When combining two int32_t with the bitwise-or operator into an
> int64_t, I've noticed that the less-significant 32 bits will contain
> something extra which will pollute the more-significant bits.
>
> gcc version/OS: (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
>
> Steps to reproduce:
> 1. Compile example in attachment:
> gcc -Wall incorrect_bitshifting.c
> No warning / error output.
> 2. Run with ./a.out
> output:
> Higher, lower: aaaa, aaaaaaaa
> result: ffffffffaaaaaaaa
> original: aaaaaaaaaaaa
>
> Expected behavior:
> Result matches original.
>
> Actual behavior:
> The upper 32 bits are polluted.
>
> Work-around:
> bitwise-and ing the lower 32 bits will provide the correct result:
> (int64_t)high_part << 32 | low_part & 0xFFFFFFFF
>