c - 将两条短裤存放在一条短裤中

标签 c data-storage

我最近写了一些代码,使用相同的 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/

上一篇:c - 理解c -'0'

下一篇:c - 函数声明

相关文章:

C 如何释放多维动态结构中的动态字符串?

c - 在 C 中验证输入

titanium - 如何使用钛在应用程序中保存数据或一组列表?

android - 私有(private)内容提供者有什么用?

c - 如何在C中用0填充数组

c++ - 是否可以在 Rust 中接收指向 C 函数的指针并将其回调?

iphone - 在同一个 iPhone 应用程序中使用两个不同的核心数据模型。我该怎么做?

java - 将数据存储在动态二维数组中

c - C中管道命令的问题

node.js - Redis 使用 node.js 占用内存