Rohit
Rohit

Reputation: 7161

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.

Upvotes: 2

Views: 3906

Answers (2)

Andreas Fester
Andreas Fester

Reputation: 36630

Because a and c are signed integers with their sign bit set, hence they are negative:

a:  1d =    1b (1 bit)
b:  2d =  010b (3 bits)
c: 13d = 1101b (4 bits)

Signed integer values are stored in two's complement, with the highest bit representing the sign (1 means "negative"). Hence, when you read the bitfield values as signed int's, you get back negative values for a and c (sign extended and converted back from their two's complement representation), but a positive 2 for b.

To get the absolute value of a negative two's complement number, you subtract one and invert the result:

 1101b
-0001b
======
 1100b

1100b inverted becomes 0011b which is equal to 3d. Since the sign bit is negative (which you had to examine before doing the previous calculation anyway), the result is -3d.

Upvotes: 2

Salgar
Salgar

Reputation: 7775

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

Upvotes: 4

Related Questions