C# - 字节数组转换为十六进制字符串
问题描述:
我正在制作现代战争2的培训师。我遇到的问题是将十六进制转换为字符串,我对此很新,但在尝试任何操作之前我都会环视四周。在发布这个问题之前,我也环顾四周。这里是我的代码:C# - 字节数组转换为十六进制字符串
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
有什么建议?
答
我认为这是一个Little-Endian vs Big-Endian的问题。请尝试以下操作:
public static string ByteArrayToString(byte[] ba)
{
if (BitConverter.IsLittleEndian)
Array.Reverse(ba);
string hex = BitConverter.ToString(ba);
return hex.Replace("-", "");
}
参考文献:
答
为什么不使用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");
}
这里看看http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa – Greenonion 2014-08-29 13:42:28
@Greenonion:你在哪里想想OP从那里得到了那个代码?无法想象许多人使用'ba'作为参数名称 – musefan 2014-08-29 13:44:34
这似乎是一个小端到大端问题。 http://people.cs.umass.edu/~verts/cs32/endian.html – wdosanjos 2014-08-29 13:46:18