我最近写了一些代码,使用相同的 unsigned short 来存储两个值,一个结果和一个 id,例如:
unsigned short data = new_id();
// result is either 0 or 1 so store it in the rightmost bit and move the id left
data = (data << 1) + get_result();
// ... later ...
// now we can print results like
printf("%u: %u\n", data & 1, data >> 1);
只使用一个结构来保存两个值会更好还是这种类型的事情很常见/可以接受?该程序已经存储了如此多的内存,我想我会开始寻找减少它使用的内存的方法。
最佳答案
Bitfields (但前提是您确实需要在空间上保持紧张 - 即嵌入式系统)?
typedef struct id_result {
unsigned int id : 15;
unsigned int result : 1;
} id_result;
否则,是的,使用具有更完整和更有意义的定义的结构:
typedef uint16 IDTYPE; /* assuming uint16 exists elsewhere */
typedef struct id_result {
IDTYPE id;
bool result;
} id_result;
关于c - 将两条短裤存放在一条短裤中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1840968/