我有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。较高的字节不受影响。
我认为这是一个标志错误,但我似乎无法修复它。
答案 0 :(得分:3)
您正在使用托管代码。 Endian-ness是框架知道的实现细节:
array<Byte>^ arr = gcnew array<Byte> { 1, 2, 3, 4 };
int value = BitConverter::ToInt16(arr, 1);
System::Diagnostics::Debug::Assert(value == 0x302);
框架的假设是否正确取决于数据的来源。
答案 1 :(得分:2)
从两个8位整数生成16位int的正确方法是value = static_cast< int16_t >( hibyte ) << 8 | lobyte;
答案 2 :(得分:1)
int y = byteArray[i] | byteArray[i + 1] << 8;
是您需要使用的。 (另见Convert a vector<unsigned char> to vector<unsigned short>)
答案 3 :(得分:0)
你想要改为
int x = UInt32(byteArray[i]) | (UInt32(byteArray[i + 1]) << 8);
你的乘数正在搞乱。
答案 4 :(得分:0)
您必须将第二个字节乘以0x0100
而不是0x00ff
。
就像在十进制系统中,你乘以十,而不是九。