【问题标题】:C# - Byte array to Hex stringC# - 字节数组到十六进制字符串
【发布时间】:2014-08-29 13:40:58
【问题描述】:

我正在为《现代战争 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

有什么建议吗?

【问题讨论】:

  • @Greenonion:你认为 OP 是从哪里得到这些代码的?想不到很多人用ba作为参数名
  • 这似乎是一个小端与大端的问题。 people.cs.umass.edu/~verts/cs32/endian.html
  • @Greenonion 已经看到了这个话题。那就是我得到转换的地方,但我很困惑从:330400000100100100000000000000 到:110000100000433
  • 仅供参考,现代战争位与问题无关。不用提了

标签: c# string hex memory-editing


【解决方案1】:

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

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

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

参考资料:

【讨论】:

    【解决方案2】:

    为什么不使用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");
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-01
      • 1970-01-01
      • 2013-08-09
      • 2013-10-13
      • 1970-01-01
      • 2011-03-25
      相关资源
      最近更新 更多