C ++:如何将数组中的2个字节转换为无符号短整型 [英] C++: how to cast 2 bytes in an array to an unsigned short
问题描述
我一直在使用一个遗留的C ++应用程序,并且绝对在我的舒适区之外(一个好东西)。我想知道是否有人会有这样的亲切给我一些指针(双关意)。
我需要在unsigned char数组中转换2个字节无符号短路。字节是连续的。
我想要做的一个例子:
我从套接字和地方收到一个字符串它在一个unsigned char数组中。我可以忽略第一个字节,然后下2个字节应转换为unsigned char。这将是在windows上只有所以没有大/小endian问题(我知道)。
这是我现在(不明显工作):
// packetBuffer是一个无符号字符数组,包含用于测试的字符串123456789
//我需要转换字节2和3到短,2是最重要的字节
//所以我希望得到515(2 * 256 + 3),而我所有的代码我试过给我
//错误或2(只转换一个字节
unsigned short myShort;
myShort = static_cast< unsigned_short>(packetBuffer [1])$ b $ b
解决方案好吧,你正在将char扩展成一个短的值,你想要的是把两个字节解释为短。
static_cast
无法从unsigned char *
转换为无符号short *
到void *
,然后到unsigned short *
:unsigned short * p = static_cast< unsigned short *>(static_cast< void *>(& packetBuffer [1]
现在,您可以取消引用p并获取短值。但是这种方法的问题是,你从unsigned char *转换为void *,然后转换为一些不同的类型。该标准不保证地址保持不变(此外,取消引用该指针将是未定义的行为)。一个更好的方法是使用位移位,它总是工作:unsigned short p =(packetBuffer [1]< < 8)| packetBuffer [2];
I have been working on a legacy C++ application and am definitely outside of my comfort-zone (a good thing). I was wondering if anyone out there would be so kind as to give me a few pointers (pun intended).
I need to cast 2 bytes in an unsigned char array to an unsigned short. The bytes are consecutive.
For an example of what I am trying to do:
I receive a string from a socket and place it in an unsigned char array. I can ignore the first byte and then the next 2 bytes should be converted to an unsigned char. This will be on windows only so there are no Big/Little Endian issues (that I am aware of).
Here is what I have now (not working obviously):
//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])
解决方案Well, you are widening the char into a short value. What you want is to interpret two bytes as an short.
static_cast
cannot cast fromunsigned char*
tounsigned short*
. You have to cast tovoid*
, then tounsigned short*
:unsigned short *p = static_cast<unsigned short*>(static_cast<void*>(&packetBuffer[1]));
Now, you can dereference p and get the short value. But the problem with this approach is that you cast from unsigned char*, to void* and then to some different type. The Standard doesn't guarantee the address remains the same (and in addition, dereferencing that pointer would be undefined behavior). A better approach is to use bit-shifting, which will always work:
unsigned short p = (packetBuffer[1] << 8) | packetBuffer[2];
这篇关于C ++:如何将数组中的2个字节转换为无符号短整型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!