Comparing Bytes to Hex?

本小妞迷上赌 提交于 2019-12-13 20:53:23

问题


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;
}

回答1:


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} ;



回答2:


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.



来源:https://stackoverflow.com/questions/6889400/comparing-bytes-to-hex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!