Byte()到.NET中的无符号整数

时间:2014-06-05 01:54:26

标签: vb.net bytestream

我第一次尝试处理数据包和字节,到目前为止,我还没有能够正确地获取数据包长度。

代码:

Public Shared Sub Client(packet As Packet)
    Console.WriteLine( _ 
      "Client -> " & _
      packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") & _
      " length:" & Convert.ToString(packet.Length))

    'Define Byte Array
    Dim clientPacket As Byte() = packet.Buffer

    ' Open a Binary Reader
    Dim memStream As MemoryStream = New MemoryStream(clientPacket)
    Dim bReader As BinaryReader = New BinaryReader(memStream)

    ' Remove the Ethernet Header
    Dim ethBytes As Byte() = bReader.ReadBytes(14)

    ' Remove the IPv4 Header
    Dim IPv4Bytes As Byte() = bReader.ReadBytes(20)

    ' Remove the TCP Header
    Dim TCPBytes As Byte() = bReader.ReadBytes(20)

    ' Get the packet length
    If clientPacket.Length > 54 Then
        Dim len As UInt32 = bReader.ReadUInt32
        Console.WriteLine(len)
    End If
End Sub

到目前为止,我所有尝试让控制台写入数据长度都导致失败。我验证了字节序,并实际写出了字节来验证我正在处理正确的数据。

示例字节:

<00> 00 00 00 24 - &gt; UINT32是36个字节,但我得到一个整数数组,如3808493568

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我同意汉斯的看法,字数是你的问题。另外,我建议您使用BitConverter数组上的clientPacket类,比使用流更容易。

Dim len As UInt32
Dim arr() As Byte
arr = {0, 0, 0, 24}
len = BitConverter.ToUInt32(arr, 0)
Console.Write(len.ToString) 'returns 402653184

arr = {24, 0, 0, 0}
len = BitConverter.ToUInt32(arr, 0)
Console.Write(len.ToString) 'returns 24

对于您的代码,我认为这可能有效(未经测试):

If clientPacket.Length > 54 Then
  Dim lenBytes As Byte() = bReader.ReadBytes(4)
  Array.Reverse(lenBytes, 0, 4)
  Dim len As UInt32 = BitConverter.ToUInt32(lenBytes, 0)