#include<stdio.h>
int main()
{
struct value{
int bit1 : 1;
int bit3 : 4;
int bit4 : 4;
}bit={1,2,2};
printf("%d %d %d\n",bit.bit1,bit.bit3,bit.bit4);
return 0;
}
Output :
-1 2 2
Please explain the oupput of the program ?
Bit fields can be used to reduce memory consumption when a program requires a number of integer variables which always will have low values. For example, in many systems storing an integer value requires two bytes (16-bits) of memory; sometimes the values to be stored actually need only one or two bits.
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. For example, consider the following declaration of date without the use of bit fields.
Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared.
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.
bit1
is a signed 1-bit integer, that can hold the values -1
and 0
only.
Presumably the only curious output is the first one.
Well, consider the range of values that a 1-bit two's-complement integer can represent.
Note the below statement inside the struct:
int bit1:1; --> 'int' indicates that it is a SIGNED integer. For signed integers the leftmost bit will be taken for +/- sign. If you store 1 in 1-bit field: The left most bit is 1, so the system will treat the value as negative number.
The 2's complement method is used by the system to handle the negative values.
Therefore, the data stored is 1. The 2's complement of 1 is also 1 (negative).
Therefore -1 is printed.
If you store 2 in 4-bits field: Binary 2: 0010 (left most bit is 0, so system will treat it as positive value) 0010 is 2 Therefore 2 is printed.
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