Johan
Johan

Reputation: 35223

Converting int32 -> hex -> string

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

Answers (3)

Tim S.
Tim S.

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

Zeph
Zeph

Reputation: 1738

Try

int i = 99;
var bits = BitConverter.GetBytes(i);
Console.Write("Char: {0}", Encoding.UTF8.GetString(bits));

Upvotes: 1

Zbigniew
Zbigniew

Reputation: 27614

You can convert it straight to char:

char myChar = (char)99;

or use:

char myChar = Convert.ToChar(99);

Upvotes: 2

Related Questions