1
#include<stdio.h>
int main()
{
    struct value
    {
    int bit1:1;
    int bit3:4;
    int bit4:4;
    }bit={1,8,15};
    printf("%d%d%d",bit.bit1,bit.bit3,bit.bit4);
    return 0;
}

The output is: -1-8-1

I know it is because of unsigned bit, but explain it more to me. Can't get why 8 prints -8 and why 15 prints -1.

Mat
  • 195,986
  • 40
  • 382
  • 396
Rahul Kathuria
  • 119
  • 2
  • 7
  • Check what is 2's complement here http://stackoverflow.com/questions/16728492/what-is-2s-complement-number/16728502#16728502 –  Aug 30 '13 at 12:33

2 Answers2

4
int bit4:4;

is signed so has range [-8..7]. Setting it to 15 is equivalent to 0b1111. Which is equivalent to -1 assuming 2s complement.

Similarly for bit3, 8 is equivalent to 0b1000. The top bit tells you this is a negative value. Inverting the other bits then adding 1 gives you -8.

If you want to store values [8..15], you either need a 5-bit signed value or to change the type to unsigned int

simonc
  • 40,917
  • 12
  • 82
  • 102
  • 1
    It is implementation-defined whether `int bit4:4;` defines a signed or unsigned bit-field (it is clearly signed **in the OP's particular case**). If you **want** a signed bit-field, write `signed int bit4:4;` C99 6.7.2:5 – Pascal Cuoq Aug 30 '13 at 12:39
1

With four bits, the sixteen bit combinations are interpreted as follows:

0000 : 0
0001 : 1
0010 : 2
0011 : 3
0100 : 4
0101 : 5
0110 : 6
0111 : 7
1000 : -8
1001 : -7
1010 : -6
1011 : -5
1100 : -4
1101 : -3
1110 : -2
1111 : -1

The numbers that you set correspond to 0001 (1), 1000 (-8) and 1111 (-1).

Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465