C Programming - Structures, Unions, Enums - Discussion
#include<stdio.h>
int main()
{
struct value
{
int bit1:1;
int bit3:4;
int bit4:4;
}bit={1, 2, 13};
printf("%d, %d, %d\n", bit.bit1, bit.bit3, bit.bit4);
return 0;
}
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.
If you store 13 in 4-bits field:
Binary 13: 1101 (left most bit is 1, so system will treat it as negative value)
Find 2's complement of 1101:
1's complement of 1101 : 0010
2's complement of 1101 : 0011 (Add 1 to the result of 1's complement)
0011 is 3 (but negative value)
Therefore -3 is printed.
So in a first bit it will take left as well as right most bit is 1 because here only 1 bit memory available.
Bit2: 4 means it will be stored 4 bit like (eg: 2 binary stored in 4 bit only).
So 4 = 0100, here left most bit is 0 that's why we didn't took 2's complement here and print value 2 as is it.
Bit3: 4 means it will be also stored 4 bit like (eg: 13 binary stored in 4 bit only).
So 13 = 1101, here left most bit is 1 that's why we took 2's complement here and print changeable value.
As you are calculating the two's complement of 13 that it's a negative number and hence you will have to append a negative sign in the answer.
Binary 13: 1101 (left most bit is 1, so system will treat it as negative value)
Find 2's complement of 1101:
1's complement of 1101 : 0010
2's complement of 1101 : 0011 (Add 1 to the result of 1's complement)
0011 is 3 (but negative value)
Therefore -3 is printed.
WHY -3? The leftmost digit is 0 so it should be 3 right?
Let's assume bit1=1 (0001)its 2's compliment is (1111) leftmost bit represents -ve value.
Because 1 is expressed as 0001 in binary. Please explain this.
So can any body help me?
Example:
a = 2 = 0010
In bit field "int a:2" means you just use 2 bit value of 0010
therefore,
int a:2 = 10.
Another example:
In bit field "int a:3" means you just use 3 bit value of 0010
therefore,
int a:2 =010.