1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

The problem of bit field in C Language

Discussion in 'C' started by wdliming, Mar 15, 2012.

  1. wdliming

    wdliming New Member

    Joined:
    Sep 26, 2010
    Messages:
    28
    Likes Received:
    0
    Trophy Points:
    0
    Today ,I have learned the bit field feature of C Language in "The C Programming Language",so I search some exercise about bit field,and then I find the C Program source code below:

    Code:
    #include <stdio.h>
    
    struct mybitfields
    {
        unsigned short a : 4;
        unsigned short b : 5;
        unsigned short c : 7;
    }test;
    
    int main(void)
    {
        int i = 0;
        test.a = 2;
        test.b = 3;
        test.c = 0;
        i = *((short *)&test);
        printf("%d",i);
        return 0;
    }
    After compile and run in X86,the result is 50!?I try to understand why,but I fail,so could some one tell me why and how get the result,thank you very much! ^@^
    (compile environment Windows XP sp3,TDM-GCC 4.6.1,X86 architecture)
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Simple. Look at the bit field like this:
    Code:
    cccccccbbbbbaaaa
    0000000000110010
    
    Now work out the decimal value of 110010: 32+16+2=what?
     
    wdliming likes this.
  3. wdliming

    wdliming New Member

    Joined:
    Sep 26, 2010
    Messages:
    28
    Likes Received:
    0
    Trophy Points:
    0
    Thank you very much! xpi0t0s!
     

Share This Page