This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Peculiar behavior with bit-shifting


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
>


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]