【问题标题】:Field packing to form a single byte字段打包形成单个字节
【发布时间】:2015-07-02 10:30:57
【问题描述】:

我正在努力学习如何将四个单独的值打包到一个字节中。我试图获得0x91 的十六进制输出,二进制表示应该是10010001,但我得到的输出分别为:0x101000116842753。或者有更好的方法吗?

uint8_t globalColorTableFlag = 1;

uint8_t colorResolution = 001;

uint8_t sortFlag = 0;

uint8_t sizeOfGlobalColorTable = 001;

uint32_t packed = ((globalColorTableFlag << 24) | (colorResolution << 16) | (sortFlag << 8) | (sizeOfGlobalColorTable << 0));

NSLog(@"%d",packed); // Logs 16842753, should be: 10010001
NSLog(@"0x%02X",packed); // Logs 0x1010001, should be: 0x91

【问题讨论】:

  • 试试 NSLog(@"%x", packed) 你会看到正在发生的事情。问题不在于算术,而在于您的 NSLog 格式。
  • @CharlieBurns 我试过了,现在我得到:1010001 缺少一个 0
  • 不,不是。您希望在哪里看到另一个零?
  • 哦,我明白了。前导零被去除。
  • 你正在制作一个 32 位整数,为什么你期望一个 8 位的值? :)

标签: objective-c c hex bitwise-operators


【解决方案1】:

尝试以下方法:

/* packed starts at 0 */
uint8_t packed = 0;

/* one bit of the flag is kept and shifted to the last position */
packed |= ((globalColorTableFlag & 0x1) << 7);
/* three bits of the resolution are kept and shifted to the fifth position */
packed |= ((colorResolution & 0x7) << 4);
/* one bit of the flag is kept and shifted to the fourth position */
packed |= ((sortFlag & 0x1) << 3);
/* three bits are kept and left in the first position */
packed |= ((sizeOfGlobalColorTable & 0x7) << 0);

有关十六进制和二进制数字之间关系的解释,请参阅此答案:https://stackoverflow.com/a/17914633/4178025

按位运算参见:https://stackoverflow.com/a/3427633/4178025

【讨论】:

  • 感谢您抽出宝贵时间回答这个问题!
【解决方案2】:
packed = ((globalColorTableFlag & 1) << 7) +
    ((colorResolution & 0x7) << 4) +
    ((sortFlag & 1) << 3) +
    ((sizeOfGlobalColorTable & 0x7);

【讨论】:

  • 你能解释一下它的作用吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-07
  • 2015-03-05
相关资源
最近更新 更多