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");
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With