gpt4 book ai didi

c# - 将 String[] 转换为 byte[] 数组

转载 作者:太空狗 更新时间:2023-10-29 18:08:37 24 4
gpt4 key购买 nike

我正在尝试将此字符串数组转换为字节数组。

string[] _str= { "01", "02", "03", "FF"};byte[] _Byte = { 0x1, 0x2, 0x3, 0xFF };

我已经尝试了下面的代码,但是它不起作用。 _Byte = Array.ConvertAll(_str, Byte.Parse);

而且,如果我可以将以下代码直接转换为字节数组,那就更好了:string s = "00 02 03 FF"byte[] _Byte = { 0x1, 0x2, 0x3, 0xFF};

最佳答案

这应该有效:

byte[] bytes = _str.Select(s => Convert.ToByte(s, 16)).ToArray();

使用 Convert.ToByte ,您可以指定要转换的基数,在您的例子中,它是 16。

如果你有一个用空格分隔值的字符串,你可以使用 String.Split拆分它:

string str = "00 02 03 FF"; 
byte[] bytes = str.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();

关于c# - 将 String[] 转换为 byte[] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com