C# - Byte array to Hex string

4.8k views Asked by At

I am making a trainer for Modern Warfare 2. The problem I am having is the conversion of hex to string, I am fairly new to this but I do look around before I try anything. I have also looked around before posting this question. Here is my code:

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("-", "");
}

The return value I am getting is: 330400000100100100000000000000

But I need it to return this: 110000100000433

Any suggestions?

2

There are 2 answers

0
Wagner DosAnjos On

I think this is a Little-Endian vs Big-Endian issue. Please try the following:

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

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

References:

0
Boz On

Why dont use 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");
}