我一直在处理一个老旧的C++应用程序,这让我感到非常不舒服(但也是好事)。我想知道是否有人能够友善地给我一些指导(双关语)。
我需要将一个无符号字符数组中的2个字节转换为一个无符号short类型。这两个字节是连续的。
举个例子,我从socket接收到一个字符串,并将其放入一个无符号字符数组中。我可以忽略第一个字节,然后将下一个2个字节转换为一个unsigned char类型。这只在Windows平台上执行,所以没有大小端问题(至少目前我不知道)。
以下是我目前的代码(显然无法工作):
//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])