Bitfield concept

struct A { int a:2; int b:3; int c:3; }; int main() { struct A p = {2,6,1}; printf("\n%d\n%d\n%d\n",pa,pb,pc); return 0; } 

Output: -2, -2.1

What will the code above output in C complier and in C ++ complier? And why?

+3
source share
4 answers

Now let's see what happens. Let's start with the given code:

 struct A { int a:3; }; int main() { struct A p = {5}; printf("%d",pa); } 

within 3 bits, the values ​​will be 101 (5), since the sign bit of this 3-bit set is 1, thus a negative value. So we need to find 2 compliments of 101, which will be 011 (3). Thus, applying the logic above, we will output as -3. Similarly, others can be proved.

eg. for 1001 (9) we will take 3 bit values ​​due to: 3. so it will be 001 (1). Since here the sign bit is not set, that is 1, so you do not need to use 2 additions. The direct answer will be 1. In the same way, others could be done.

+1
source

Your system uses 2 add-ons . Holding a 2 bit 2-bit field will be 10 in binary format, which is -2 in a 2 complement system. Similarly, 110(6) is -2 for a 3-bit representation in 2 additions. And 1 is simple 1

Also read about signed bit fields here.

+5
source

I get -2 -2 1 with my C compiler. The problem is that your bit fields are too small for the numbers you are trying to store. In the first two cases, the leftmost bits are 1, so they are interpreted as negative numbers. To fix this, follow these steps:

  • Increase the bit fields.
  • Declare your bit fields as unsigned ints instead of ints
  • Before printing, go to unsigned int and use% u to print.
+3
source

You get answers for the same reason as this program:

 #include <stdio.h> #include <stdint.h> int main(void) { int32_t a = 4294967294; printf("%d\n", a); return 0; } 

Has a conclusion of -2 . Initializing a signed variable with too many to interpret in different ways. From the specification:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is determined by the implementation, or a signal is generated that is determined by the implementation.

+1
source

All Articles