use*_*784 19 c++ pointers casting
我一直致力于传统的C++应用程序,我绝对不在我的舒适区域(一件好事).我想知道是否有人会非常友好地给我一些指示(双关语).
我需要将unsigned char数组中的2个字节转换为unsigned short.字节是连续的.
有关我想要做的事情的一个例子:
我从套接字接收一个字符串并将其放在unsigned char数组中.我可以忽略第一个字节,然后接下来的2个字节应转换为unsigned char.这将只在Windows上,因此没有Big/Little Endian问题(我知道).
这就是我现在拥有的(显然不是很明显):
//packetBuffer is an unsigned char array containing the string "123456789" for testing
//I need to convert bytes 2 and 3 into the short, 2 being the most significant byte
//so I would expect to get 515 (2*256 + 3) instead all the code I have tried gives me
//either errors or 2 (only converting one byte
unsigned short myShort;
myShort = static_cast<unsigned_short>(packetBuffer[1])
Run Code Online (Sandbox Code Playgroud)
Joh*_*itb 22
好吧,你正在将char扩大为一个短值.你想要的是将两个字节解释为short.static_cast无法投射unsigned char*到unsigned short*.你必须施展void*,然后unsigned short*:
unsigned short *p = static_cast<unsigned short*>(static_cast<void*>(&packetBuffer[1]));
Run Code Online (Sandbox Code Playgroud)
现在,您可以取消引用p并获取短值.但是这种方法的问题是你从unsigned char*转换为void*然后转换为某种不同的类型.标准不保证地址保持不变(此外,解除引用该指针将是未定义的行为).更好的方法是使用位移,这将始终有效:
unsigned short p = (packetBuffer[1] << 8) | packetBuffer[2];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37736 次 |
| 最近记录: |