Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain the behaviour of 1-bit bit-fields

Tags:

c

#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 ?

like image 348
dark_shadow Avatar asked Apr 10 '12 18:04

dark_shadow


People also ask

What are bit fields explain with example?

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.

What is the characteristic of bit fields in C?

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.

What are bit fields in C Explain with syntax?

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.

What is bit field in programming?

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.


3 Answers

bit1 is a signed 1-bit integer, that can hold the values -1 and 0 only.

like image 116
Daniel Fischer Avatar answered Sep 22 '22 12:09

Daniel Fischer


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.

like image 25
Oliver Charlesworth Avatar answered Sep 23 '22 12:09

Oliver Charlesworth


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.

like image 41
Amitesh Purohit Avatar answered Sep 23 '22 12:09

Amitesh Purohit