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?
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?
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 byte
s, so you'll need to do some partitioning of your array first.
01000001 01000010 01000011 01000100
which in decimal is "1094861636", the value that the uint
would contain.
BitConverter.ToUInt32
is little endian, so 1145258561
is the correct decimal value for an input of "ABCD"
. You can reverse the array before calling BitConverter.ToUInt32
and you will get the decimal value I gave above, which corresponds to 41424344
in hex.
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