c++ - c++ 将四个 unsined char 转换为一个 unsigned int
问题描述
在我的 c++ 程序中,我有一个包含四个unsigned char
成员的结构
struct msg
{
unsigned char zero; unsigned char one; unsigned char two; unsigned char three;
}
并创建了一个结构数组
msg myMsg[4] = {{0x11,0x22,0xAA,0xCC},{...},{...},{...}};
现在在一个函数中,我想将此数组的索引作为unsigned int
unsigned int procMsg(int n){
return myMsg[n]; // of course this is worng
}
像这样的值:0xCCAA2211
解决方案
考虑一下:
像这样的消息:{0x01, 0x01, 0x01, 0x01}
可以解析为
00000001 00000001 00000001 00000001(bin) = 16.843.009(dec)
所以你只需要获取每个字符并根据其位置移动它们,即
char0 完全没有移动,
char1 向左移动 8 个位置(或乘以 2^8)
char2 向左移动 16 个位置(或乘以 2^(8*2))
char3 向左移动 24 个位置(或乘以 2^(8*3))
unsigned int procMsg(Message &x)
{
return (x.three << 24) |
(x.two << 16) |
(x.one << 8) |
x.zero;
}
int main(int argc, char *argv[])
{
//0 1 2 3
Message myMsg[4] = {{0x01, 0x01, 0x01, 0x01}, //00000001 00000001 00000001 00000001 = 16.843.009
{0xFF, 0x00, 0xAA, 0xCC}, //00000001 00000001 00000001 00000001 = 3.433.693.439
{0x01, 0x00, 0x00, 0x00}, //00000001 00000001 00000001 00000001 = 1
{0x00, 0x00, 0x00, 0x00} //00000000 00000000 00000000 00000000 = 0
};
for (int i = 0; i<4; i++)
{
Message x = myMsg[i];
std::cout << "res: " << procMsg(myMsg[i]) << std::endl;
}
return 0;
}
推荐阅读
- r - 如何考虑来自 http://www.ranks.nl/stopwords 的“长停用词列表”?
- clojure - 使用重载的相同数量方法创建抽象 java 类的 clojure 代理
- constraints - CPLEX 数学模型转换为代码
- mongodb - 如何自动配置 mongodb 副本集
- python - 在 Windows 上安装 psycopg2 时出错
- python - 用python覆盖mongodb中的json文件
- mysql - 如何在sql中查找每个员工从开始日期开始的总工作时间?
- xcode - 架构 x86_64 的未定义符号:“_OBJC_CLASS_$_GeneratedPluginRegistrant”
- javascript - 香草 javascript 和 css 图像滑块无法正常工作
- android - 为什么在 altBeacon 库中使用区域时无法获得完整的 uuid?