Field packing to form a single byte

I'm struggling to learn how to pack four seperate values into a single byte. I'm trying to get a hex output of 0x91 and the binary representation is supposed to be 10010001 but instead I'm getting outputs of: 0x1010001 and 16842753 respectively. Or is there a better way to do this?

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

打包的领域


Try the following:

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

For an explanation about the relation between hexadecimal and binary digits see this answer: https://stackoverflow.com/a/17914633/4178025

For bitwise operations see: https://stackoverflow.com/a/3427633/4178025


packed = ((globalColorTableFlag & 1) << 7) +
    ((colorResolution & 0x7) << 4) +
    ((sortFlag & 1) << 3) +
    ((sizeOfGlobalColorTable & 0x7);
链接地址: http://www.djcxy.com/p/72664.html

上一篇: 了解按位运算符并对它们进行比较

下一篇: 字段打包形成一个字节