Search code examples
cstructurebitbit-fields

C programming bitfield in structure


Why is answer of it

-1, 2, -3 ?  (especially -3 ??? how come)

struct b1 {
    int a:1;
    int b:3;
    int c:4;
} ;
int  main()
{
    struct b1 c = {1,2,13};
    printf("%d, %d, %d",c.a,c.b,c.c);
    return 0;
}

Compiled on VC++ 32 bit editor. Many Thanks.


Solution

  • signed integers are represented in twos complement. The range of a 1-bit twos complement number is -1 to 0. Because the first bit of a twos complement number indicates it is negative, which is what you have done there.

    See here: sign extend 1-bit 2's complement number?

    That is the same for the third number, you have overflowed the range of -8 to 7 which is the range of a 4 bit signed integer.

    What you meant to do there is make all of those int -> unsigned int

    See here for twos complement explanation: http://www.ele.uri.edu/courses/ele447/proj_pages/divid/twos.html