简体   繁体   English

C#将string转换为uint

[英]C# convert string to uint

So, I have a string of 13 characters. 所以,我有一个13个字符的字符串。

string str = "HELLOWORLDZZZ";

and I need to store this as ASCII representation (hex) in a uint variable. 我需要将它作为ASCII表示(十六进制)存储在一个uint变量中。 How do I do this? 我该怎么做呢?

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

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

You can use Encoding.ASCII . 您可以使用Encoding.ASCII . GetBytes to convert your string to a byte array with ASCII encoding (each character taking one byte ). GetBytes将您的字符串转换为ASCII编码的byte数组(每个字符占用一个byte )。 Then, call BitConverter.ToUInt32 to convert that byte array to a uint . 然后,调用BitConverter.ToUInt32将该字节数组转换为uint However, as @R. 但是,作为@R。 Bemrose noted in the comments, a uint is only 4 byte s, so you'll need to do some partitioning of your array first. Bemrose在评论中指出, uint只有4 byte ,所以你需要先对数组进行一些分区。

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: 请参阅我的评论,但如果您只想将ASCII字符串转换为Hex,这是我怀疑的:

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;
}

这会将您的string (使用Base 16表示形式)转换为uint

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

Now I guess I understand what you want in a comment on bdukes answer. 现在我想我明白了你对bdukes答案的评论。

If you want the hex code for each character in the string you can get it using LINQ. 如果你想要字符串中每个字符的hex代码,你可以使用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 hex将是一个字符串41424344

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM