2位大小可变 [英] 2 bits size variable
问题描述
我需要定义一个结构,它具有大小2位和6位的数据成员。
我应该为每个成员使用 char
类型吗?或者,为了不浪费内存,我可以使用:2
\ :6
符号?
我该怎么做呢?
我可以为2或6位类型定义一个typedef吗?
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 something like :2
\ :6
notation?
how can I do that?
Can I define a typedef for 2 or 6 bits type?
推荐答案
>
You can use something like:
typedef struct {
unsigned char SixBits:6;
unsigned char TwoBits:2;
} tEightBits;
,然后使用:
tEightBits eight;
eight.SixBits = 31;
eight.TwoBits = 3;
但是,老实说,除非你必须遵守应用程序外部的打包数据,或者您处于非常内存限制的情况,这种内存节省通常不值得。如果不需要一直使用bitwise和bithift操作来打包和解压缩数据,您会发现代码的速度要快得多。
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.
还要记住,使用除 _Bool
, signed int
或 unsigned int
是实现的问题。具体来说, unsigned char
可能无处不在。
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.
这篇关于2位大小可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!