how to stop bit-field sign extension

Falk Hueffner
Mon Sep 29 20:01:00 GMT 2003

Kevin Nomura <> 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
(, this cast gets ignored.  As a workaround,
try assigning the bitfield value to an unsigned variable first and
shift it then.


More information about the Gcc-help mailing list