在 C++ 中将 unsigned char(字节)数组转换为 unsigned Short
我有 array^ byteArray ,我需要提取 Little Endian 序列中的字节以生成无符号短整型和整数。我已经尝试了以下我能想到的所有组合,因此寻求帮助。
int x = UInt32(byteArray[i]) + (UInt32)(0x00ff) * UInt32(byteArray[i + 1]);
int x = UInt32(byteArray[i]) + UInt32(0x00ff) * UInt32(byteArray[i + 1]);
int x = byteArray[i] + 0x00ff * byteArray[i + 1];
问题是最低有效字节(在 i+1 处),我知道它是 0x50,但生成的 Short/int 报告低字节为 0x0b。高字节不受影响。
我认为这是一个符号错误,但我似乎无法修复它。
I have array^ byteArray
and I need to extract bytes in Little Endian sequence to make unsigned shorts and ints. I've tried every combination of the following I can think of so am asking for help.
int x = UInt32(byteArray[i]) + (UInt32)(0x00ff) * UInt32(byteArray[i + 1]);
int x = UInt32(byteArray[i]) + UInt32(0x00ff) * UInt32(byteArray[i + 1]);
int x = byteArray[i] + 0x00ff * byteArray[i + 1];
The problem is the least significant byte (at i+1) I know it is 0x50 but the generated short/int reports the lower byte as 0x0b. The higher byte is unaffected.
I figure this is a sign error but I can't seem to be able to fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您正在使用托管代码。 Endian-ness 是框架了解的实现细节:
框架的假设是否正确取决于数据来自何处。
You are using managed code. Endian-ness is an implementation detail that the framework is aware of:
Whether the framework's assumptions are correct depends on where the data came from.
从两个 8 位整数生成 16 位整数的正确方法是
value = static_cast
int16_t >( hibyte ) << 8 |洛字节;
The proper way to generate an 16 bit int from two 8 bit ints is
value = static_cast< int16_t >( hibyte ) << 8 | lobyte;
是你需要使用的。 (另请参阅将向量转换为向量)
is what you need to use. (see also Convert a vector<unsigned char> to vector<unsigned short>)
你想这样做
你的乘数把事情搞砸了。
You want to do this instead
Your multipliers are messing things up.
您必须将第二个字节乘以
0x0100
而不是0x00ff
。就像在十进制中,你乘以十,而不是九。
You have to multiply the second byte with
0x0100
instead of0x00ff
.It's like in the decimal system, where you multiply by ten, not by nine.