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: how to stop bit-field sign extension


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


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