我正在努力学习如何将四个单独的值打包成一个字节。我试图获得0x91
的十六进制输出,二进制表示应该是10010001
,而是我得到的输出:0x1010001
和{{1 }} 分别。或者有更好的方法吗?
16842753
答案 0 :(得分:2)
尝试以下方法:
/* 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
答案 1 :(得分:0)
packed = ((globalColorTableFlag & 1) << 7) +
((colorResolution & 0x7) << 4) +
((sortFlag & 1) << 3) +
((sizeOfGlobalColorTable & 0x7);