Reputation: 35223
I'm reading an integer from the memory (i
below). To convert it in to the character that I'm after I do the following:
int i = 99;
string hex = 99.ToString("X"); //"63"
string readable = hex.FromHex(); //"c"
public static string FromHex(this string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return Encoding.UTF8.GetString(raw);
}
But I suppose there is an easier way to accomplish this?
Upvotes: 0
Views: 209
Reputation: 56586
This should work, assuming UTF8 encoding:
byte[] bytes = BitConverter.GetBytes(i).Where(x => x != 0).ToArray();
string result = Encoding.UTF8.GetString(bytes);
But take note that the endianness of the machine(s) you run this on matters.
Upvotes: 1
Reputation: 1738
Try
int i = 99;
var bits = BitConverter.GetBytes(i);
Console.Write("Char: {0}", Encoding.UTF8.GetString(bits));
Upvotes: 1
Reputation: 27614
You can convert it straight to char
:
char myChar = (char)99;
or use:
char myChar = Convert.ToChar(99);
Upvotes: 2