Byte() إلى عدد صحيح غير موقع في .NET
-
21-12-2019 - |
سؤال
لقد حاولت التعامل مع الحزم والبايتات لأول مرة، ولم أتمكن من الحصول على طول الحزمة بشكل صحيح حتى الآن بعد العديد من التقنيات المختلفة.
شفرة:
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
حتى الآن، كل محاولاتي لجعل وحدة التحكم تكتب طول البيانات باءت بالفشل.لقد قمت بالتحقق من صحة endianness وقمت بالفعل بكتابة البايتات للتحقق من أنني كنت أتعامل مع البيانات الصحيحة.
مثال بايت:
00 00 00 24 -> UINT32 هو 36 بايت، ولكنني أحصل على مجموعة من الأعداد الصحيحة مثل 3808493568
كيف يمكنني اصلاح هذا؟
المحلول
وأنا أتفق مع هانز، إنديانيس هي مشكلتك.كما أنصحك باستخدام 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)
لا تنتمي إلى StackOverflow