From textBox string to hex 0x bytes [] C #

Possible duplicate:
How to convert byte array to hexadecimal string and vice versa in C #?

I have a text box that enters the string "AA 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF", I split it into String [], but now I need to get byte [] like this:

byte[] b6 = new byte[20] {0xAA,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88 ,0x99 ,0xAA ,0xBB,0xCC ,0xDD ,0xEE,0xFF}; 

can someone tell me how to do this. I tried using Convert.ToByte , but I get the error of not being able to convert String to byte. And I don't need to convert the values ​​in hexadecimal, just to add 0x before each byte and add to the byte array.

+4
source share
4 answers
 string input = "AA 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF"; byte[] bytes = input.Split().Select(s => Convert.ToByte(s, 16)).ToArray(); 
+1
source

Try

 int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); 

for each broken line item and add it to the list.

 List<Byte> bytes = new List<Byte>(); foreach (var splittedValue in hexString.Split(' ')) { bytes.Add(int.Parse(splittedValue, System.Globalization.NumberStyles.HexNumber)); } return bytes.ToArray(); 
+1
source

You can use byte.Parse :

 byte[] bytes = str.Split().Select(s => byte.Parse(s, NumberStyles.HexNumber)).ToArray(); 

To display bytes in hexadecimal notation, use ToString override:

 foreach (var b in bytes) { Console.WriteLine("0x{0:X}", b); //or Console.WriteLine("0x" + b.ToString("X")); } 

You can also use the "X" format and its modifications in string.Format .

0
source

you can use tostring

-1
source

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


All Articles