Signed Bitfields

J

John J. Smith

Here's a question about (signed) bitfields that's been bothering me for
decades. With

struct {
unsigned int bar:1;
} foo;

, foo.bar's range is obviously 0 and 1.

On 2s complement architectures,

struct {
signed int bar:1;
} foo;

allowed values are -1 and 0, which means foo.bar's only bit is
obviously the sign bit.

Now, on sign/magnitude arches, wouldn't that make the two only
valid values -0 and 0, which on top of that are required to compare
equal? If not, how are any other two values supposed to fit into
one bit?
 
A

Army1987

Here's a question about (signed) bitfields that's been bothering me for
decades. With

struct {
unsigned int bar:1;
} foo;

, foo.bar's range is obviously 0 and 1. Yes.
On 2s complement architectures,

struct {
signed int bar:1;
} foo;

allowed values are -1 and 0, which means foo.bar's only bit is
obviously the sign bit.
Yes. Note that, with 2's complement, 10...00 is allowed to be a
trap representation (in which case INT_MIN will be 10...01, i.e.
-INT_MAX), and then a one in that bitfield would be a trap
representation.
Now, on sign/magnitude arches, wouldn't that make the two only valid
values -0 and 0, which on top of that are required to compare equal?
Yes. Note that, with 1s' complement and with sign-and-magnitude,
11...11 is allowed to be a trap representation (in which case the
implementation won't support integer negative zeroes), and then
a one in that bitfield would be a trap representation.
If not, how are any other two values supposed to fit into one bit?
They don't. Use unsigned for boolean bitfield. It is the only
portable way to make them able to hold a nonzero value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top