将字节与十六进制进行比较? [英] Comparing Bytes to Hex?

查看:170
本文介绍了将字节与十六进制进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将UDP数据包的前5个字节与两个定义进行比较,并根据它们对其进行相应处理。然而,我应该如何表示十六进制,因为这显然不会/不工作?



被评论的行是我原来的做法,但不是非常高效。

pre $ private static void HandleQuery(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);
返回字节;


private bool CompareByteArray(byte [] a1,byte [] a2,int len)
{
for(int i = 0; i< len; i ++)
{
if(a1 [i]!= a2 [i])
{
return false;
}
}

返回true;


解决方案

更容易:

  // byte [] A2S_PLAYER = StringToByteArray(\xFF\xFF\xFF\xFF\ X55\" ); 
byte [] A2S_PLAYER =新字节[] {0xFF,0xFF,0xFF,0xFF,0x55​​};


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

这篇关于将字节与十六进制进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆