0

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?

3 Answers 3

2

You can convert it straight to char:

char myChar = (char)99;

or use:

char myChar = Convert.ToChar(99);
Sign up to request clarification or add additional context in comments.

5 Comments

I may be wrong, but I don't think this decodes using UTF8 encoding, but UTF16. Might not matter if you're only dealing with ordinary characters like c.
Well, this works for ordinary characters like c. Which I assume to be the case (since Johan hasn't mentioned more).
It should also work for other characters, e.g. you can try to replace 99 with 1337. It will produce Թ character.
@TimS.: I believe the original approach is fundamentally broken anyway. It's unclear what the OP is really trying to achieve, but I suspect this may be it.
Yup, to clarify it's "a", "b", "c" and "d". So works perfect for me. Thanks
1

Try

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.