一短存两条短裤

use*_*033 0 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);
Run Code Online (Sandbox Code Playgroud)

使用结构来保存这两个值或者这种类型的东西是常见/可接受的会更好吗?该程序已经存储了如此多的内存,我以为我开始想办法减少它耗尽的内存.

pli*_*nth 13

Bitfields(但只有你真的需要在空间上紧张 - 即嵌入式系统)?

typedef struct id_result {
    unsigned int id : 15;
    unsigned int result : 1;
} id_result;
Run Code Online (Sandbox Code Playgroud)

否则,是的,使用具有更完整和有意义定义的结构:

typedef uint16 IDTYPE; /* assuming uint16 exists elsewhere */

typedef struct id_result {
    IDTYPE id;
    bool result;
} id_result;
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您应该使用unsigned int而不是int,因为单个位上的int只能包含值0或-1. (2认同)

Pau*_*lin 7

除非记忆非常紧张,否则我会去结构路线.对于必须维护代码的下一个人来说,这样更清晰,更容易.

我想起了M68000有32位地址寄存器的时间,但实际上只使用了24位地址寄存器.程序员做了各种"优化"来将信息存储在其他8位中.当芯片的后期版本(如M68030)使用全部32位时,男孩脸色都是红色的.

  • +1.把维护者想象成一个挥舞着疯子的斧头,知道你住在哪里. (3认同)