Thursday September 16, 2004
#include <stdio.h>
struct foo {
int thirtyone:31;
int bit:1;
};
struct foo one = {0 , 1};
struct foo zero = {0 , 0};
int
return_bit(struct foo *p)
{
return (p->bit);
}
int
main(int argc, char **argv)
{
printf("one %x\n", return_bit(&one));
printf("zero %x\n", return_bit(&zero));
}
Running the above when compiled with the Sun compiler gave:
$; ./bitfield one 1 zero 0and gcc gave:
$; ./bitfield-gcc one ffffffff zero 0Clearly gcc has sign extended the value which broke the real code I had. Making the bit field unsigned is obviously the right thing to do (as it is unsigned) but it has left me wondering which compiler is right or whether both are and this is a grey area.
Except where otherwise noted, this site is
licensed under a Creative Commons License 2.0
This is a personal weblog, I do not speak for my employer.
| « December 2009 | ||||||
| Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|
1 | 3 | 4 | 5 | 6 | ||
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 | |||
| Today | ||||||
Posted by Calum Mackay on September 16, 2004 at 10:33 PM BST #
So this is implementation-defined, which means an implementation has to document how it behaves. And Sun's compiler says in C user's guide:
C.1.9 J.3.9 Structures, Unions, Enumerations, and Bit-fields * Whether a "plain" int bit-field is treated as signed int bit-field or as an unsigned int bit-field (6.7.2, 6.7.2.1). It is treated as an unsigned int.Unfortunately, gcc's info page doesn't say anything about this (other than the standard says it is implementation defined) - it's possible that my copy of gcc is slightly outdated (3.4.2) or it is documented somewhere else. So I don't know whether gcc documents this behavior somewhere but clearly it treats int as signed int.Posted by Seongbae Park on September 16, 2004 at 10:33 PM BST #
Posted by Calum Mackay on September 16, 2004 at 10:44 PM BST #