Min0
Min0

Reputation: 150

Converting hex string back to char

I know- there are lots of topics concerning this, BUT even though I did look through a bunch of them couldn't figure the solution.. I'm converting char to hex like this:

char c = i;
int unicode = c;
string hex = string.Format("0x{0:x4}", unicode);

Question: how to convert hex to char back?

Upvotes: 8

Views: 17753

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40155

using System;
using System.Globalization;

class Sample {
    static void Main(){
        char c = 'あ';
        int unicode = c;
        string hex = string.Format("0x{0:x4}", unicode);
        Console.WriteLine(hex);
        unicode = int.Parse(hex.Substring(2), NumberStyles.HexNumber);
        c = (char)unicode;
        Console.WriteLine(c);
    }
}

Upvotes: 3

Marco
Marco

Reputation: 57593

You could try:

hex = hex.Substring(2); // To remove leading 0x
int num = int.Parse(hex, NumberStyles.AllowHexSpecifier);
char cnum = (char)num;

Upvotes: 20

Related Questions