【问题标题】:assignment of packed bitfield struct gives wrong values打包位域结构的赋值给出了错误的值
【发布时间】: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


【解决方案1】:

问题是从参数列表中看到的值(由于参数的提升)将是无符号整数(32 位)。然后错误的行试图将 32 位无符号整数复制到 16 位短整数中。

通常这会起作用,但是 pragma 会修改 16 位颜色在提升参数中的放置方式和/或代码如何引用 16 位颜色。

While packed values are (normally) not promoted,
if there is no prototype for the called function
then all parameters are assumed to 'int' 
so the code assumes the data is (sizeof int) bytes long (4 bytes)
and the assignment takes the last 2 bytes
of that 4 byte value rather than the first 2 bytes.

【讨论】:

  • 这听起来很合理:当我重写分配以分配单个字段,然后更改分配顺序时,我会得到不同的结果。多么令人沮丧,有没有办法以我想要的方式使用这些位域? (用于命名颜色通道并重新解释视频内存中的投射像素)
猜你喜欢
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多