2 bits size variable

前端 未结 3 1705
夕颜
夕颜 2020-12-19 10:48

I need to define a struct which has data members of size 2 bits and 6 bits. Should I use char type for each member?Or ,in order not to waste a memory,can I use

3条回答
  •  醉酒成梦
    2020-12-19 11:10

    You can use something like:

    typedef struct {
        unsigned char SixBits:6;
        unsigned char TwoBits:2;
    } tEightBits;
    

    and then use:

    tEightBits eight;
    eight.SixBits = 31;
    eight.TwoBits = 3;
    

    But, to be honest, unless you're having to comply with packed data external to your application, or you're in a very memory constrained situation, this sort of memory saving is not usually worth it. You'll find your code is a lot faster if it's not having to pack and unpack data all the time with bitwise and bitshift operations.


    Also keep in mind that use of any type other than _Bool, signed int or unsigned int is an issue for the implementation. Specifically, unsigned char may not work everywhere.

提交回复
热议问题