字段包装以形成一个单一的字节 [英] Field packing to form a single byte

查看:145
本文介绍了字段包装以形成一个单一的字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我努力学习如何Pack的四种单独的值到一个字节。我试图让 0x91的信息的十六进制输出和二进制再presentation应该是 10010001 分别为 0x1010001 16842753 :而是我得到的输出。还是有更好的方式来做到这一点?

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

推荐答案

请尝试以下操作:

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

有关十六进制和二进制数字看到这个答案之间的关系作出解释:<一href=\"http://stackoverflow.com/a/17914633/4178025\">http://stackoverflow.com/a/17914633/4178025

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

有关位操作请参见: http://stackoverflow.com/a/3427633/4178025

这篇关于字段包装以形成一个单一的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆