Explain the behavior of single-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; } 

Exit:

-1 2 2

Please explain about the program?

+7
source share
3 answers

Presumably the only curious way out is the first.

Well, consider a range of values ​​that a single integer two's-complement can represent.

+8
source

bit1 is a signed one-bit integer that can only contain -1 and 0 .

+9
source

Note the following statement inside the struct:

int bit1: 1; β†’ 'int' indicates that it is a SIGNED integer. For signed integers, the left-most bit will be taken as the +/- sign. If you store 1 in a 1-bit field: The leftmost bit is 1, so the system will treat the value as a negative number.

The 2-padding method used by the system to process negative values.

Therefore, the stored data is 1. 2 additions 1 are also 1 (Negative).

Therefore -1 is printed.

If you store 2 in a 4-bit field: Binary 2: 0010 (the most recent bit is 0, so the system will consider it as a positive value) 0010 is 2 Therefore, 2 is printed.

+2
source

All Articles