Using bits with int in structure

#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 this so? what exactly does int: 4 do? Please explain

+6
source share
4 answers

Since there are two additions , the highest order bit is used for the sign. By writing a:4 , you say that you only allocate 4 bits of memory, which leaves 3 bits left for the actual number. Therefore, our effective range is [-8,7] . Since all 1 is -1, there is an additional number on the negative side. See the link above for more details.

9, in (unsigned) binary code: 1001 . When you put this in a (signed), you get that a negative, because of the initial 1, and since the next numbers are 001 , we add 1 to the maximum negative number, thereby giving us - 7.

If you want to keep the number 9 in just 4 bits, you need to use unsigned int , which will give you a range of [0, 15] .

EDIT:
In case someone struggles with figuring out how 1001 signed up, gives us -7, consider the following:

Since 1111 is -1, let some variable value = -1 .

To find out the values ​​of the negative (signed) int num , denote x i in num :

x i : {0,1 at position i, where i = 0 is the least significant bit)},

Then for each x i = 0, subtract 2 i from value .

Example:

1001 :

value = -1 - 2 1 - 2 2 = -7

+5
source

Your field is an integer with a 4-bit sign. For signed integers, the top bit is a signed bit, which means that for the actual number you only have 3 bits. The range of numbers that you can save in the field is from -8 to 7 (subject to 2 repositories of compliments).

The bit pattern for 9 is 1001, which has the 4th bit bit, that is, it is interpreted as a negative number, so it prints as -7. If you were expecting -1, you need to read 2 compliments .

If you want to keep 9 in the field, do a a unsigned int

+4
source

You reserved only 4 bits for the field, one bit is used for the sign, so only 3 bits remain for positive values. This way you can only store up to 7.

+3
source

you need to use unsigned really int :

 #include<stdio.h> struct a { unsigned a:4; // <-- unsigned indeed int, then work good }; main(){ struct a aa; aa.a=9; printf("a=%d\n",aa.a); return 0; } 

output:

  a=9 
+2
source

Source: https://habr.com/ru/post/949378/


All Articles