简体   繁体   中英

Turn string with numbers to byte array - C#

I created string that contains numbers by calling string.Join on a byte array:

string str = string.Join(", ", arr);

(arr is a byte array).

How can I turn the string back to a byte array?

You can use String.Split and then Byte.Parse to parse the string, eg :

var newArray = str.Split(',').Select(Byte.Parse).ToArray();

Byte.Parse ignores whitespace so there's no need to trim

If you create the array like this :

var str = String.Join(", ", new byte[]{0xFF,0x05,0x56});

The new array produced by splitting:

var newArray = Split(',').Select(Byte.Parse).ToArray();

Will contain the values 255, 5 and 86.

Assuming your string looks like "1,2,3,4"

var numArray = str.Split(',').Select(s => Byte.Parse(s)).ToArray();

Runnable:

https://rextester.com/XOMQ99840

Not sure what the down vote is for. Shrug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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