C# - 字节数组为十六进制字符串

时间:2014-08-29 13:40:59

标签: c# string hex memory-editing

我正在为现代战争制作培训师2.我遇到的问题是将十六进制转换为字符串,我对此很新,但在尝试任何事情之前我都会环顾四周。在发布这个问题之前我也环顾四周。这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    int xbytesRead = 0;
    byte[] myXuid = new byte[15];
    ReadProcessMemory((int)processHandle, xuidADR, myXuid, myXuid.Length, ref xbytesRead);
    string xuid = ByteArrayToString(myXuid);
    textBox2.Text = xuid;
}

public static string ByteArrayToString(byte[] ba)
{
    string hex = BitConverter.ToString(ba);
    return hex.Replace("-", "");
}

我得到的返回值是:330400000100100100000000000000

但我需要它来回复:110000100000433

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

我认为这是Little-Endian与Big-Endian的问题。请尝试以下方法:

public static string ByteArrayToString(byte[] ba)
{
    if (BitConverter.IsLittleEndian)
         Array.Reverse(ba);

    string hex = BitConverter.ToString(ba);
    return hex.Replace("-", "");
}

参考文献:

答案 1 :(得分:0)

为什么不使用int?

private void button1_Click(object sender, EventArgs e)
{
int xbytesRead = 0;
byte[] myXuid = new byte[15];
ReadProcessMemory((int)processHandle, xuidADR, myXuid, myXuid.Length, ref xbytesRead);
string xuid = ByteArrayToString(myXuid);
textBox2.Text = xuid;
}

public static string ByteArrayToString(byte[] ba)
{
  int hex=0;
  for(i=0;i<ba.Length;i++)
     hex+=Convert.ToInt(ba[i])*Math.Pow(256,i)
  return hex.ToString("X");
}