gpt4 book ai didi

objective-c - 字段打包形成一个字节

转载 作者:太空宇宙 更新时间:2023-11-04 02:43:15 25 4
gpt4 key购买 nike

我正在努力学习如何将四个单独的值打包到一个字节中。我正在尝试获取 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

Packed Field

最佳答案

尝试以下操作:

/* 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

关于objective-c - 字段打包形成一个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29836990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com