How about 1 bit signed variable?

Programming, for all ages and all languages.
Post Reply
NOTNULL

How about 1 bit signed variable?

Post by NOTNULL »

Hello all,
Consider, I am declaring a 1 bit bit-field variable as,
int bit:1. Signed variable should have 1 bit alloted for the sign. What about in bit-field operator? If i store 1 in the bit-field variable, will it be the value or just a sign.

Any help appreciated
mpp.eox3

Re:How about 1 bit signed variable?

Post by mpp.eox3 »

The answer is just a try in a compiler away......

union {
unsigned bar;
struct {
int onebit : 1;
};
} foo;

foo.bar = 0;
cout << "onebit: " << foo.onebit << "\n";
foo.bar = 1;
cout << "onebit: " << foo.onebit << "\n";

This will give the following output:
onebit: 0
onebit: -1


If you want some more explanation on this:

In your computer, signed numbers are stored in 2-complement form - so the highest bit is not reserved to be "just a sign". Actually, it's used for the number too but you can use it to determine the sign.
Note that there are number formats with an explicit reserved bit for the sign. On these formats, the sign bit has no effect on the absolute value of the number. The only place where this is used in your computer is the floating point formats.

Take a look at this 8 bit signed number in 2complement format:
01111111 = 127
10000000 = -128
10000001 = -127
10010000 = -128 + 16 = -112
The bit values for a 2complement 8bit number are:
-128, 64, 32, 16, 8, 4, 2, 1

..And for a 2complement 1bit number:
-1

So to answer your question, the variable onebit can hold the values 0 and -1.
Post Reply