This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: how to stop bit-field sign extension
- From: Falk Hueffner <falk dot hueffner at student dot uni-tuebingen dot de>
- To: Kevin Nomura <nomura at netapp dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: 29 Sep 2003 22:01:38 +0200
- Subject: Re: how to stop bit-field sign extension
- References: <20030929185947.GV9917@bughouse.netapp.com>
Kevin Nomura <nomura@netapp.com> writes:
> What does it mean to have an unsigned bit-field if sign extension
> can still occur in a case such as this:
>
> [siml4]$ cat a.c
> struct foo {
> unsigned int a:16;
> } x;
>
> main()
> {
> unsigned long long ll;
> x.a = 0x8000;
> ll = x.a << 16; /* (unsigned int) x.a does not help */
> printf ("%llx\n", ll);
> }
>
> [siml4]$ gcc a.c
> [siml4]$ a.out
> ffffffff80000000
The rule is very simple -- all values of unsigned int a:16 fit into an
int, so it is promoted to int, just like short or unsigned short are.
Therefore, you need the cast to unsigned. Unfortunately, it does not
help with gcc since due to of the most long-standing bugs in gcc
(http://gcc.gnu.org/PR3325), this cast gets ignored. As a workaround,
try assigning the bitfield value to an unsigned variable first and
shift it then.
--
Falk