Concept of bit field - c

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",p.a,p.b,p.c);
return 0;
}
Output is:
-2,-2,1
What would be output of above code in C complier and in C++ complier?
And Why?

Your system seems to using 2's complement. A 2-bit bit-field holding 2 would be 10 in binary which is -2 in 2's complement system. Likewise 110(6) is -2 for a 3-bit representation in 2's complement. And 1 is plain 1
Also read about signed bit-fields here

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's, so they are interpreted as negative numbers. To fix this, either:
Make your bit fields larger
Declare your bit fields as unsigned ints instead of ints
Cast to unsigned int before printing and use %u to print.

You get those answers for the same reason that this program:
#include <stdio.h>
#include <stdint.h>
int main(void)
{
int32_t a = 4294967294;
printf("%d\n", a);
return 0;
}
Has output -2. Initializing a signed variable with a number too large to fit causes it to be interpreted differently. From the spec:
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

Now Lets see what exactly is happening. Lets start with the given code:
struct A
{
int a:3;
};
int main()
{
struct A p = {5};
printf("%d",p.a);
}
within 3 bits the values would be 101(5) since sign bit of this 3 bit set is 1 thus negative value. Thus we need to find 2's compliment of 101 which would be 011(3).
Thus by applying above logic we would output as -3. Similarly others could be proved.
e.g. for 1001(9) we shall take 3 bit values because of a:3. thus it would be 001(1). Since here sign bit is not set i.e. 1 so no need to use 2's complement. Straight forward answer would be 1.
Similarly others could be done.

Related

Negative power of 2

I am learning the characteristics of the different data type. For example, this program increasingly prints the power of 2 with four different formats: integer, unsigned integer, hexadecimal, octal
#include<stdio.h>
int main(int argc, char *argv[]){
int i, val = 1;
for (i = 1; i < 35; ++i) {
printf("%15d%15u%15x%15o\n", val, val, val, val);
val *= 2;
}
return 0;
}
It works. unsigned goes up to 2147483648. integer goes up to -2147483648. But why does it become negative?
I have a theory: is it because the maximum signed integer we can represent on a 32 bit machine is 2147483647? If so, why does it return the negative number?
First of all, you should understand that this program is undefined. It causes signed integer overflow, and this is declared undefined in the C Standard.
The technical reason is that no behavior can be predicted as different representations are allowed for negative numbers and there could even be padding bits in the representation.
The most probable reason you see a negative number in your case is that your machine uses 2's complement (look it up) to represent negative numbers while arithmetics operate on bits without overflow checks. Therefore, the highest bit is the sign bit, and if your value overflows into this bit, it turns negative.
What you describe is UB caused by integer overflow. Since the behavior is undefined, anything could happen (“When the compiler encounters [a given undefined construct] it is legal for it to make demons fly out of your nose”), BUT, what actually happens on some machines (I suspect yours included) is this:
You start with int val = 1;. That is represented 0b00...1 in binary form. Each time you val *= 2; the value is multiplied by 2, therefore the representation changes to 0b00...10 and then to 0b00...100 and so on (the 1 bit moves one step each time). The last time you val *= 2; you get 0b100.... Now, using 2's complement (which is what I guess your machine uses, as it very common) the value is actually -1 * 0b1000... which is -2147483648
Note, that even though this might be what's really going on in your machine, it's not to be trusted or thought of as the "right" thing to happen, since, as mentioned before, this is UB
In this program, the val value will overflow, if it is a 32- bit machine, because the size of integer is 4 bytes. Now, we have 2 type of values in math, positive and negative, so to do calculation involving negative results, we use sign representations i.e int or char in C language.
Lets take the example of char, range -128 to 127, unsigned char range 0-255 .
It tells, range is divided into two parts for signed representation. So for any signed variable, if it crosses its range of +ve value, it goes into negative value. Like here in case of char, as the value goes above the 127, it becomes -ve. And suppose if you add 300 to any char or unsigned char variable what happens, it rolls over and starts again from zero.
char a=2;
a+=300;
what is the value?? now you know max value of char is 255(total 256 values, including zero), so 300-256 = 44 + 2 =46.
Hope this helps

Signed and Unsigned program error

So today am learning about the signed and unsigned variables. So what i can make out is that signed can have positive, negative and zero values and unsigned can have only the positive values.
So to try this through code i wrote this program in c:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int a=-10;
unsigned int x=-4;
printf("signed variable value is : %d\n Unsigned variable value is : %u",a,x);
}
SO as per my expectation output should be like this :
signed variable value is : -10
Unsigned variable value is : 4
But in reality it turned out to be like this:
signed variable value is : -10
Unsigned variable value is : 4294967292
Can any one explain this !!
When you assign a negative value into a unsigned int and print it using the format specifier %u, 2's complement of that number will be taken into consideration.
So that x become 2's complement of -4, ie 4294967292
A similar question is asked here
Assigning negative numbers to an unsigned int?
The way that unsigned variables work is that they wrap around past 0 (both going forward and back), treating 0 as congruent to 232 (on a 32-bit system). To see this, try the following program:
#include <stdio.h>
int main()
{
unsigned int test = 3;
for (int i = 0; i < 10; ++i)
{
test = test - 1;
printf("%u\n", test);
}
}
Output (on a 32-bit system):
2
1
0
4294967295
4294967294
4294967293
4294967292
4294967291
4294967290
4294967289
Back to your code. -4 is of course the same as 0 - 4 so what you have gotten is the fourth item past 0 on this list.
NB. Your code does not have any errors apart from void main
The unsigned variable doesn't take the absolute value for you.
Since you are putting a negative value in it, it casts the signed integer value (-4) to a 4 byte unsigned variable.
I am guessing the negative values are stored as 2's complement here. Therefore what you get as a -4 on a unsigned 4byte variable is in fact 2^32 -4 (one wrap around) : 4294967292

How does C store negative numbers in signed vs unsigned integers?

Here is the example:
#include <stdio.h>
int main()
{
int x=35;
int y=-35;
unsigned int z=35;
unsigned int p=-35;
signed int q=-35;
printf("Int(35d)=%d\n\
Int(-35d)=%d\n\
UInt(35u)=%u\n\
UInt(-35u)=%u\n\
UInt(-35d)=%d\n\
SInt(-35u)=%u\n",x,y,z,p,p,q);
return 0;
}
Output:
Int(35d)=35
Int(-35d)=-35
UInt(35u)=35
UInt(-35u)=4294967261
UInt(-35d)=-35
SInt(-35u)=4294967261
Does it really matter if I declare the value as signed or unsigned int? Because, C actually only cares about how I read the value from memory. Please help me understand this and I hope you prove me wrong.
Representation of signed integers is up to the underlying platform, not the C language itself. The language definition is mostly agnostic with regard to signed integer representations. Two's complement is probably the most common, but there are other representations such as one's complement and signed magnitude.
In a two's complement system, you negate a value by inverting the bits and adding 1. To get from 5 to -5, you'd do:
5 == 0101 => 1010 + 1 == 1011 == -5
To go from -5 back to 5, you follow the same procedure:
-5 == 1011 => 0100 + 1 == 0101 == 5
Does it really matter if I declare the value as signed or unsigned int?
Yes, for the following reasons:
It affects the values you can represent: unsigned integers can represent values from 0 to 2N-1, whereas signed integers can represent values between -2N-1 and 2N-1-1 (two's complement).
Overflow is well-defined for unsigned integers; UINT_MAX + 1 will "wrap" back to 0. Overflow is not well-defined for signed integers, and INT_MAX + 1 may "wrap" to INT_MIN, or it may not.
Because of 1 and 2, it affects arithmetic results, especially if you mix signed and unsigned variables in the same expression (in which case the result may not be well defined if there's an overflow).
An unsigned int and a signed int take up the same number of bytes in memory. They can store the same byte values. However the data will be treated differently depending on if it's signed or unsigned.
See http://en.wikipedia.org/wiki/Two%27s_complement for an explanation of the most common way to represent integer values.
Since you can typecast in C you can effectively force the compiler to treat an unsigned int as signed int and vice versa, but beware that it doesn't mean it will do what you think or that the representation will be correct. (Overflowing a signed integer invokes undefined behaviour in C).
(As pointed out in comments, there are other ways to represent integers than two's complement, however two's complement is the most common way on desktop machines.)
Does it really matter if I declare the value as signed or unsigned int?
Yes.
For example, have a look at
#include <stdio.h>
int main()
{
int a = -4;
int b = -3;
unsigned int c = -4;
unsigned int d = -3;
printf("%f\n%f\n%f\n%f\n", 1.0 * a/b, 1.0 * c/d, 1.0*a/d, 1.*c/b);
}
and its output
1.333333
1.000000
-0.000000
-1431655764.000000
which clearly shows that it makes a huge difference if I have the same byte representation interpreted as signed or unsigned.
#include <stdio.h>
int main(){
int x = 35, y = -35;
unsigned int z = 35, p = -35;
signed int q = -35;
printf("x=%d\tx=%u\ty=%d\ty=%u\tz=%d\tz=%u\tp=%d\tp=%u\tq=%d\tq=%u\t",x,x,y,y,z,z,p,p,q,q);
}
the result is:
x=35 x=35 y=-35 y=4294967261 z=35 z=35 p=-35 p=4294967261 q=-35 q=4294967261
the int number store is not different, it stored with Complement style in memory,
I can use 0X... the 35 in 0X00000023, and the -35 in 0Xffffffdd, it is not different you use sigend or unsigend. it only output with different sytle. The %d and %u is not different about positive, but the negative the first position is sign, if you output with %u is 0Xffffffdd equal 4294967261, but the %d the 0Xffffffdd can be - 0X00000023 equal -35.
The most fundamental thing that variable's type defines is the way it is stored (that is - read from and written to) in memory and how are the bits interpreted, so your statement can be considered "valid".
You can also look at the problem using conversions. When you store signed and negative value in unsigned variable it gets converted to unsigned. It so happens that this conversion is reversible, so signed -35 converts to unsigned 4294967261, which - when you request it - can be converted to signed -35. That's how 2's complement encoding (see link in other answer) works.

Structure with signed integer bit-fields resulting minus outputs

This is the C code with a struct.
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct{
int a : 4;
unsigned int b : 3;
int c : 3;
} x;
x.a = 7;
x.b = 7;
x.c = 7;
printf("%d\n",x.a);
printf("%d\n",x.b);
printf("%d\n",x.c);
return 0;
}
In the above C program x.c has allocated 3 bits from memory but resulting an output result as -1. What is the reason for this?
data member c is defined as having type int (that is signed int in case of your compiler) and have only 3 bits to represent signed values. So the most significant bit is considered as the sign bit, 7 in the binary notation looks as
111
where the left-most bit is used as the sign bit due to the definition
int c : 3;
So this combination of bits means that the number is negative and equal to -1.
The maximum positive value that can be stored in this bit field is equal to 3
011
and the minimum negative value is equal to -4
100
Take into account that it is implementation defined whether a bit field defined as having type int will be interpretated as unsigned int or signed int. Your compiler consideres a bit field of type int as having type signed int
So it is better to explicitly specify either signed int or unsigned int for bit fields.
From the C Standard
...except that for bitfields, it is implementation-defined whether the
specifier int designates the same type as signed int or the same type
as unsigned int.
In two's complement, -1 is represented as 11111111......... {as many as number of bits }
When you assign 7, which is 111 in binary, the sign bit gets 1, and remaining bits get 1 and 1.
Now,
sign bit = 1 => number is negative
remaining bits = 11 => 1 in two's complement.
Hence the result is negative one
note: from the behavior, it appears your machine implements two's complement
The difference between an int and unsigned datatype is the significance of the sign bit. In the above code, you are using int for x.c with 3 bits to store the value 7, which in binary translates to 111. When you print the value in x.c, using %d, it is taken as the sign bit to be set. If you are on a little-endian machine and if you initialize it with any value higher than 4, you would be setting the sign bit and getting a result of two's complement as MAKZ said in his answer.
so
7 will print as -1, 6 will print as -2, 5 will print as -3, 4 will print as -4

Bit field manipulation-setting a bit

#include<stdio.h>
int main()
{
struct s{
int bit_fld:3;
};
s a;
a.bit_fld=0x10;
a.bit_fld =( a.bit_fld | (1<<2));
printf("%x\n",a.bit_fld);
return 0;
}
This program outputs fffffffc.
I tried to do manual calculation of the output and I could not get the output that the compiler produced.
bit_fld = 00010000 and (1<<2) = 0100 oring both wil result in 00010100 which is 0x14 in hexadecimal.
Why my perception of the output is wrong ? Help me to understand where I'm mistaken.
a.bit_fld is only 3 bits big, it can't store the value 0x10. Behavior is implementation-defined, but in this case it has probably stored 0.
Then 1 << 2 is binary 100 as you say. Assuming we did store 0 at the first step, the result of ( a.bit_fld | (1<<2)) is an int with value 4 (binary 100).
In a signed 2's complement 3-bit representation, this bit pattern represents the value -4, so it's not at all surprising if -4 is what you get when you store the value 4 to a.bit_fld, although again this is implementation-defined.
In the printf, a.bit_fld is promoted to int before passing it as a vararg. The 2's complement 32 bit representation of -4 is 0xfffffffc, which is what you see.
It's also undefined behavior to pass an int instead of an unsigned int to printf for the %x format. It's not surprising that it appears to work, though: for varargs in general there are certain circumstances where it's valid to pass an int and read it as an unsigned int. printf isn't one of them, but an implementation isn't going to go out of its way to stop it appearing to work.

Resources