This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Packing Bytes

Hi,

The literature I'm reading suggests that I can specify the number of bits a certain data type must occupy, and that I can possibly store several of these packed variables into the same byte for reduced storage space.

typedef struct{
unsigned int a: 4;
unsigned char b: 2;
} my_type;

I tried the above but it just truncates the values assigned and stores them in separate two byte wide and 1 byte wide spaces respectively. What's the trick?

Regards,
Murray R. Van Luyn.

Parents
  • The problem is that you've changed sizes of the integers into which the bit fields are supposed to be packed; the first is an int, and the second a char. This tells the compiler that you really do want two different integers, 2 bytes and 1 byte respectively.

    Try

    typedef struct
        {
        unsigned int a: 4;
        unsigned int b: 2;
        } my_type;
    

    and the compiler will pack all 6 bits into the same int. (Declaring both fields as unsigned char will pack into 8 bits.)

    Note that ANSI C insists that all bitfields occupy the space of a "int", regardless of how few bits are used. Most compilers allow the programmer to specify types other than int to avoid wasting space. In this sense, Keil C is more flexible than the standard. But as always, with minor power comes minor responsibility.

    Searching the forum will bring up other threads discussing bitfields and the usual pitfalls with their use, thanks largely to the definition being under-constrained by the standard.

Reply
  • The problem is that you've changed sizes of the integers into which the bit fields are supposed to be packed; the first is an int, and the second a char. This tells the compiler that you really do want two different integers, 2 bytes and 1 byte respectively.

    Try

    typedef struct
        {
        unsigned int a: 4;
        unsigned int b: 2;
        } my_type;
    

    and the compiler will pack all 6 bits into the same int. (Declaring both fields as unsigned char will pack into 8 bits.)

    Note that ANSI C insists that all bitfields occupy the space of a "int", regardless of how few bits are used. Most compilers allow the programmer to specify types other than int to avoid wasting space. In this sense, Keil C is more flexible than the standard. But as always, with minor power comes minor responsibility.

    Searching the forum will bring up other threads discussing bitfields and the usual pitfalls with their use, thanks largely to the definition being under-constrained by the standard.

Children