簡體   English   中英

在C#中將2個字節轉換為Short

[英]Converting 2 bytes to Short in C#

我正在嘗試將兩個字節轉換為無符號短路,以便我可以檢索實際的服務器端口值。 我是根據回復格式下的協議規范做出的。 我嘗試使用BitConverter.ToUint16() ,但問題是,它似乎沒有拋出預期值。 請參閱下面的示例實現:

int bytesRead = 0;

while (bytesRead < ms.Length)
{
    int first = ms.ReadByte() & 0xFF;
    int second = ms.ReadByte() & 0xFF;
    int third = ms.ReadByte() & 0xFF;
    int fourth = ms.ReadByte() & 0xFF;
    int port1 = ms.ReadByte();
    int port2 = ms.ReadByte();
    int actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port1 , (byte)port2 }, 0);
    string ip = String.Format("{0}.{1}.{2}.{3}:{4}-{5} = {6}", first, second, third, fourth, port1, port2, actualPort);
    Debug.WriteLine(ip);
    bytesRead += 6;
}

給定一個樣本數據,假設對於兩個字節值,我有105和135,轉換后的預期端口值應該是27015,而是使用BitConverter得到值34665。

我這樣做是錯誤的嗎?

如果您反轉BitConverter調用中的值,您應該得到預期的結果:

int actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port2 , (byte)port1 }, 0);

在小端架構上,低位字節需要在數組中位於第二位。 正如lasseespeholt在評論中指出的那樣,你需要在大端架構上顛倒順序。 可以使用BitConverter.IsLittleEndian屬性檢查。 或者,使用IPAddress.HostToNetworkOrder可能是一個更好的解決方案(首先轉換該值,然后調用該方法將字節放入正確的順序,而不管字節順序如何)。

BitConverter正在做正確的事情,你只需要低字節和高字節混合 - 你可以手動使用bitshift進行驗證:

byte port1 = 105;
byte port2 = 135;

ushort value = BitConverter.ToUInt16(new byte[2] { (byte)port1, (byte)port2 }, 0);
ushort value2 = (ushort)(port1 + (port2 << 8)); //same output

要處理小端和大端架構,您必須執行以下操作:

if (BitConverter.IsLittleEndian)
    actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port2 , (byte)port1 }, 0);
else
    actualPort = BitConverter.ToUInt16(new byte[2] {(byte)port1 , (byte)port2 }, 0);

暫無
暫無

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

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