c# - BitConverter.ToString() 反过来?

标签 c# .net

<分区>

我有一个字节数组,我想将其存储为一个字符串。我可以这样做:

byte[] array = new byte[] { 0x01, 0x02, 0x03, 0x04 };
string s = System.BitConverter.ToString(array);

// Result: s = "01-02-03-04"

到目前为止一切顺利。有谁知道我如何将其返回数组?没有采用字符串的 BitConverter.GetBytes() 重载,将字符串分解为字符串数组然后转换每个字符串似乎是一种令人讨厌的解决方法。

有问题的数组可能是可变长度的,大概有 20 个字节。

最佳答案

不是内置方法,而是实现。 (虽然它可以在没有拆分的情况下完成)。

String[] arr=str.Split('-');
byte[] array=new byte[arr.Length];
for(int i=0; i<arr.Length; i++) array[i]=Convert.ToByte(arr[i],16);

没有拆分的方法:(对字符串格式做了很多假设)

int length=(s.Length+1)/3;
byte[] arr1=new byte[length];
for (int i = 0; i < length; i++)
    arr1[i] = Convert.ToByte(s.Substring(3 * i, 2), 16);

还有一种方法,既没有拆分也没有子串。如果您将此提交给源代码管理,您可能会被 Gunicorn 。我对此类健康问题不承担任何责任。

int length=(s.Length+1)/3;
byte[] arr1=new byte[length];
for (int i = 0; i < length; i++)
{
    char sixteen = s[3 * i];
    if (sixteen > '9') sixteen = (char)(sixteen - 'A' + 10);
    else sixteen -= '0';

    char ones = s[3 * i + 1];
    if (ones > '9') ones = (char)(ones - 'A' + 10);
    else ones -= '0';

    arr1[i] = (byte)(16*sixteen+ones);
}

(基本上实现两个字符的base16转换)

关于c# - BitConverter.ToString() 反过来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1230303/

相关文章:

c# - 无法添加到 IPgedList 对象或将 List<T> 传输到 IPgedList<T>

c# - 如果我的接口(interface)必须返回 Task 什么是无操作实现的最佳方法?

.net - 国际化 .NET 应用程序

c# - 使用C#将文件复制到HDFS Hadoop环境

c# - 如何确定我的应用程序是否处于事件状态(有焦点)

c# - 谷歌身份验证 C#

c# - 将固定长度的数字转换为十进制.NET C#

c# - 使用 Parallel.ForEach 和 Task.Factory.StartNew 之间的主要区别是什么

c# - 无法从 xtragridview 获取点击行的数据

c# - 如何 reshape 形态?