【发布时间】:2015-03-31 15:51:18
【问题描述】:
我有一个应该是 16 位的压缩结构:
#pragma pack(1)
typedef unsigned int uint;
typedef unsigned short ushort;
typedef struct Color Color;
struct Color
{
uint r : 5;
uint g : 5;
uint b : 5;
uint _ : 1;
};
我已经确认了
&(((Color*)0x06000000)[x]) == &(((ushort*)0x06000000)[x])
对于 x 的各种值。但是,在这段代码中,这两行给了我不同的结果。
void write_pixel (uint x, uint y, Color color)
{
#if 0
((Color*)0x06000000)[x+y*240] = color;
#else
((ushort*)0x06000000)[x+y*240] = ((ushort*)&color)[0];
#endif
}
第二个选项是正确的。
可能是什么原因?
注意。我正在为 GBA 模拟器进行编译,所以没有调试器或 printf,只有通过绿色/红色像素的 yes/no 语句。
【问题讨论】:
-
你得到什么结果?在这个平台上短是 16 位吗?(只是检查)
-
如果我 write_pixel (0,31,31) 我使用第二条路径得到一个青色像素,但使用第一条路径得到一个白色像素。我很确定这个平台上的 short 是 16 位,但无论如何,Color 结构和 unsigned short 的大小是一样的。
-
为什么不使用
int16_t并确定? -
刚试了一下,大小一样。
-
你已经验证了结构是你认为的大小?您可以计算指定的 16 个字节,但由于对齐,实际大小不一定是 16。
标签: c