开发者

C# convert string to uint

So, I have a string of 13 characters.

string str = "HELLOWORLDZZZ";

and I need to store this as ASCII repre开发者_StackOverflowsentation (hex) in a uint variable. How do I do this?


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.


I think this is the method you want

Convert.ToUInt32(yourHexNumber, 16);

see the documentation here.


uint.Parse(hexString, System.Globalization.NumberStyles.HexNumber);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜