How can I convert a string to byte [] from unsigned int 32 C #

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

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

I thought about splitting a string into,, and then to it, and setvalue to another byte[] in index i

 string Key = "0x5D, 0x50, 0x68, 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 it looks like it is not working. I get an error in converting a string to unsigned int32 on first start.

any help would be appreciated

+4
source share
3 answers

You can do the following:

 byte[] data = Key .Split(new string[]{", "}, StringSplitOptions.None) .Select(s => Byte.Parse(s.Substring(2), NumberStyles.HexNumber)) .ToArray(); 
+5
source
 keybyte[i] = byte.Parse(arr[i].Trim().Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); 
+3
source

You must explicitly specify AllowHexSpecifier (or HexNumber - see the documentation below for more details). In addition, the hexadecimal strings that must be passed to Parse cannot have the 0x prefix, so you need to strip them first.

From MSDN Documentation :

Indicates that a numeric string represents a hexadecimal value. Valid hexadecimal values ​​include the numeric digits 0-9 and the hexadecimal digits AF and af. Hexadecimal values ​​can be left with zeros. Lines processed using this style are not allowed with the prefix "0x".

So try:

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

In addition, you mentioned the use of an unsigned integer. Did you mean to use UInt32 instead?

Also, you don't know why you called the extra ToString on string ...

0
source

Source: https://habr.com/ru/post/1311072/


All Articles