簡體   English   中英

在C ++中將無符號字符(字節)數組轉換為無符號short

[英]Convert array of unsigned char (byte) into unsigned short in C++

我有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。 高位字節不受影響。

我認為這是一個符號錯誤,但似乎無法修復。

您正在使用托管代碼。 Endian-ness是框架了解的實現細節:

array<Byte>^ arr = gcnew array<Byte> { 1, 2, 3, 4 };
int value = BitConverter::ToInt16(arr, 1);
System::Diagnostics::Debug::Assert(value == 0x302);

框架的假設是否正確取決於數據來自何處。

從兩個8位整數生成16位整數的正確方法是value = static_cast< int16_t >( hibyte ) << 8 | lobyte; value = static_cast< int16_t >( hibyte ) << 8 | lobyte;

int y = byteArray[i] | byteArray[i + 1] << 8;

是您需要使用的。 (另請參見將vector <unsigned char>轉換為vector <unsigned short>

您想這樣做

int x = UInt32(byteArray[i]) | (UInt32(byteArray[i + 1]) << 8);

您的乘數使事情變得混亂。

您必須將第二個字節乘以0x0100而不是0x00ff

就像在十進制系統中,您乘以十而不是九。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM