2
#include<stdio.h>
main()
{
  struct value
   {
      int bit1 : 1;
      int bit2 : 4;
      int bit3 : 4;
   }bit={1, 2, 2};

  printf("%d %d %d\n",bit.bit1,bit.bit2,bit.bit3);
}

Output of this code is "-1 2 2" Please clarify the logic behind this output. Value of bit.bit2 and bit.bit3 is always same as the value assigned to it but bit.bit1 is changing with different integer values. why?

1
  • the most significant bit because used as the sign bit. Commented Jul 7, 2013 at 9:11

4 Answers 4

4

You should use unsigned int. The highest bit, defines whether a number is negative or positive if signed values are used. If you have only one bit, and this is 1, then it it is interpreted as a negative number as the highest bit is set.

If you set the other values to 15 you will also get a negative output.

You could modify the output by using %u in the printf command, but you would still have possibly unwanted effects when assigning and comparing it with other values.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I am new to C can you please explain what is the meaning of "int bit1: 1" ? What this is exactly doing?
If you want to work with individual bits, you can decalre bitfields. So your structure is treated as if it holds only a single bit, instead of an int having 16-32bits (depending on the hardware). This is more convenient then having to mask the bits yourself when you want to set/unset them. It's also conventient if you work with hardware so you can overlay it with a structure.
1

int x : b ; means you are allocating only b bits of memory to x instead of the default sizeof(int) bytes. This kind of declaration is only possible inside a structure.
Range of signed integer in C is -2^(b-1) to 2^(b-1)-1. Where b is number of bits used to store the integer. In all the above cases overflow occurs. A good compiler should give you a warning about overflow.

Comments

0

A signed bit-field of size 1 accepts values in the range [-1 … 0]. This is a consequence of the general formula [-2^(N-1) … 2^(N-1)-1] for determining the range of values that can be stored in N bits with 2's complement representation for N=1.

If you expected bit1 to hold the values 0 or 1, you can declare it as unsigned int bit1 : 1;.

Comments

0

The standard does not specify whether int in bit-fields is signed or unsigned. Instead, it forces you to explicitly specify signedness.

A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.