#include<stdio.h>
struct a
{
int a:4;
};
main(){
struct a aa;
aa.a=9;
printf("a=%d\n",aa.a);
return 0;
}
Here the output is -7. Why is it so? what does exactly int a:4 does ? please explain
In programming terminology, a bit field is a data structure that allows the programmer to allocate memory to structures and unions in bits in order to utilize computer memory in an efficient manner. Since structures and unions are user-defined data types in C, the user has an idea of how much memory will they occupy.
Bit fields CANNOT be used in union.
Pointers and non-const references to bit-fields are not possible.
In C, we can specify size (in bits) of structure and union members. The idea is to use memory efficiently when we know that the value of a field or group of fields will never exceed a limit or is within a small range.
Since it's two's complement, the highest order bit is used for the sign. By writing a:4
you're saying to only allocate 4 bits of memory, which leaves 3 bits left over for the actual number. So our effective range is [-8,7]
. Since all 1's is -1, there's an extra number on the negative side. For more of an explanation on this, see the above link.
9, in (unsigned) binary is: 1001
. When you put this into a
(signed), you get that a
is negative, due to the initial 1, and since the following numbers are 001
, we add 1 to the max negative number, thereby giving us -7.
If you want to store the number 9 in only 4 bits, you need to use an unsigned int
, which would give you a range of [0, 15]
.
EDIT:
In case anyone is struggling with figuring out how 1001
signed gives us -7, consider the following:
Since 1111
is -1, let some variable value = -1
.
To figure out the values of a negative (signed) int num
, let us denote xi in num
:
xi : {0,1 at position i, where i=0 is the least significant bit)},
Then, for every xi = 0, subtract 2i from value
.
Example:
1001
:
value
= -1 - 21 - 22 = -7
Your field is a 4 bit signed integer. For signed integers the upper bit is a sign bit, which means that you only have 3 bits for the actual number. The range of numbers you can store in the field are -8 to 7 (assuming 2's compliment storage).
The bit pattern for 9 is 1001, which has the 4th bit set, meaning it is interpreted as a negative number, which is why it is printing out as a -7. If you would have expected a -1, you need to read up on 2's compliment.
If you want to be able to store 9 in the field, make a
an unsigned int
You only reserved 4 bits for the field, one bit is used for the sign, so only 3 bits remain for positive values. Thus you can only store values up to 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With