开发者

How can i convert a string into byte[] of unsigned int 32 C#

I have a string like "0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF". I want to convert it into:

byte[] key= new byte[] { 0x5D, 0x50, 0x68, 0xBE, 0xC9, 0xB3, 0x84, 0xFF};

I thought about splitting the string by , then loop on it and setvalue into another byte[] in index of i

string Key = "0x5D, 0x50, 0x6开发者_如何学Python8, 0xBE, 0xC9, 0xB3, 0x84, 0xFF";

    string[] arr = Key.Split(',');
    byte[] keybyte= new byte[8];
    for (int i = 0; i < arr.Length; i++)
    {
         keybyte.SetValue(Int32.Parse(arr[i].ToString()), i);
    }

but seems like it doesn't work. I get error in converting the string into unsigned int32 on the first beginning.

any help would be appreciated


You can do like this:

byte[] data =
  Key
  .Split(new string[]{", "}, StringSplitOptions.None)
  .Select(s => Byte.Parse(s.Substring(2), NumberStyles.HexNumber))
  .ToArray();


keybyte[i] = byte.Parse(arr[i].Trim().Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);


You have to explicitly specify AllowHexSpecifier (or HexNumber - see the documentation below for details). Also, hex strings to be passed to Parse cannot have the 0x prefix, so you'll have to strip them out first.

From MSDN Documentation:

Indicates that the numeric string represents a hexadecimal value. Valid hexadecimal values include the numeric digits 0-9 and the hexadecimal digits A-F and a-f. Hexadecimal values can be left-padded with zeros. Strings parsed using this style are not permitted to be prefixed with "0x".

So try:

Int32.Parse(arr[i].Substring(2), 
    System.Globalization.NumberStyles.AllowHexSpecifier)

Also, you mentioned using an unsigned integer. Did you mean to use UInt32 instead?

Additionally, not sure why you were calling an additional ToString on a string...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜