Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# convert hexadecimal value in to UTF8 and ASCII

I am trying to convert a hexadecimal values in a string in to both ASCII value and UTF8 value. But when I execute the following code, it prints out the same hex value I give as input

string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
byte[] dBytes = encoding.GetBytes(hexString);

//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");

//To get the UTF8 value of the hex string
string utf8result = System.Text.Encoding.UTF8.GetString(dBytes);
MessageBox.Show(utf8result, "Showing value in UTF8");
like image 603
D P. Avatar asked Feb 16 '23 04:02

D P.


1 Answers

Since you are naming a variable hexString, I assume that the value is already encoded into a hex format.

This means the following will not work:

string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
byte[] dBytes = encoding.GetBytes(hexString);

This is because you are treating the already encoded string as plain UTF8 text.

You are probably missing a step to convert the hex encoded string into a byte array.

You can do this using this SO post which shows this function:

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length/2;
  byte[] bytes = new byte[NumberChars];
  using (var sr = new StringReader(hex))
  {
    for (int i = 0; i < NumberChars; i++)
      bytes[i] = 
        Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
  }
  return bytes;
}

So, the end result would be this:

byte[] dBytes = StringToByteArray(hexString);

//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");

//To get the UTF8 value of the hex string
string utf8result = System.Text.Encoding.UTF8.GetString(dBytes);
MessageBox.Show(utf8result, "Showing value in UTF8");
like image 65
Davin Tryon Avatar answered Feb 17 '23 21:02

Davin Tryon