If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Re: Question about unions,bitfields

Originally Posted by 2kaud

int is a signed number.

Yeah, I agree to that being the probable reason for the failure. I didn't really test/investigate this, but I think a one-bit signed integer made up by such a bit field quasi comprises a sign bit only. If that bit is set and that gets sign-extended to one of the common signed integer types with more bits, the result will probably be -1. So I think the OP's signed int code would work if it were changed to comparison against -1 rather than 1.

I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

Re: Question about unions,bitfields

first of all, this is all implementation defined behavior. Even the signedness of an "int" bitfield is implementation defined ( you should write "signed int" to enforce a signed integer, although int and signed int are always the same type ... don't ask me why ). It's also implementation defined how they are packed/aligned or if they are stored from left to right or vice versa, etc ...

regarding your observed behavior, in two-complement a signed bitfield of n-bits gives a range of values [-2^(n-1),+2^(n-1)-1]; for a 1-bit-field this means a range [-1,0].

Re: Question about unions,bitfields

1) the standard defines bitfields only for unsigned int, int and signed int. other types may or may not be supported by your compiler
2) the standard only defines the behaviour of bitfields.
3) the standard does not define actual implementation of how the bits are packed into the large type. hence bitfields are compiler dependant and are not binary portable.
If your application requires specific implementation of sequences of bits stored into a larger type, you need to shift/mask yourself, bitfields are NOT a portable solution for this.
4) there is no such thing as a "sign bit" in C++ or at least not one that is guaranteed. most computers store negative numbers as 2's complement some store it as one's complement. Because of this. bitfields of 1 bit in a signed type make little sense and even behaviour isn't guaranteed to be portable in this case.
On a One complement machine a 1 bit signed bitfield will hold either 0 or 1, on a Two's complement machine it will hold -1 or 0.