Comparing Bytes to Hex?
I need to compare the first 5 bytes of a UDP packet to two definitions, and act on them accordingly if it matches one. However, how should I represent the Hex for this since this obviously won't/isn't working?
The commented lines are the original way I was doing it, but not very efficient.
private static void HandleQuery(Socket socket, EndPoint Remote)
{
byte[] A2S_INFO_REQUEST = StringToByteArray("\xFF\xFF\xFF\xFF\x54");
byte[] A2S_PLAYER = StringToByteArray("\xFF\xFF\xFF\xFF\x55");
byte[] data = new byte[1400];
int recv = socket.ReceiveFrom(data, ref Remote);
// A2S_INFO QUERY
//if (recv == 25 && data[4] =开发者_如何学编程= 84)
if (CompareByteArray(A2S_INFO_REQUEST, data, 5))
{
ReplyInfoQuery(socket, Remote);
}
// A2S_PLAYER QUERY
//if (recv == 9)
if (CompareByteArray(A2S_PLAYER, data, 5))
{
ReplyPlayerQuery(socket, Remote);
}
}
private static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
private static bool CompareByteArray(byte[] a1, byte[] a2, int len)
{
for (int i = 0; i < len; i++)
{
if (a1[i] != a2[i])
{
return false;
}
}
return true;
}
You can fill a byte array easier:
//byte[] A2S_PLAYER = StringToByteArray("\xFF\xFF\xFF\xFF\x55");
byte[] A2S_PLAYER = new byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x55} ;
I'd suggest to convert your 5 bytes in a long (System.Int64). That way you can even use a switch/case to dispatch your requests.
精彩评论