简体   繁体   中英

Explain the behaviour of 1-bit bit-fields

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM