Question

So, I have a string of 13 characters.

string str = "HELLOWORLDZZZ";

and I need to store this as ASCII representation (hex) in a uint variable. How do I do this?

Was it helpful?

Solution

You can use Encoding.ASCII.GetBytes to convert your string to a byte array with ASCII encoding (each character taking one byte). Then, call BitConverter.ToUInt32 to convert that byte array to a uint. However, as @R. Bemrose noted in the comments, a uint is only 4 bytes, so you'll need to do some partitioning of your array first.

OTHER TIPS

Have a look at Convert.ToUInt32(string, int). For example:

uint parsed = Convert.ToUInt32(str, 16);
uint.Parse(hexString, System.Globalization.NumberStyles.HexNumber);

I think this is the method you want

Convert.ToUInt32(yourHexNumber, 16);

see the documentation here.

See my comment, but if you want to just convert an ASCII string to Hex, which is what I suspect:

public string HexIt(string yourString)
{
    string hex = "";
    foreach (char c in yourString)
    {
        int tmp = c;
        hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}

This will convert your string (with a Base 16 representation) to a uint.

uint val = Convert.ToUInt32(str, 16);

Now I guess I understand what you want in a comment on bdukes answer.

If you want the hex code for each character in the string you can get it using LINQ.

var str = "ABCD";
var hex = str.Select(c => ((int)c).ToString("X"))
    .Aggregate(String.Empty, (x, y) => x + y);

hex will be a string 41424344

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top