问题描述
我有,我想存储为一个字符串的字节数组。我能做到这一点,如下所示:
I have an array of bytes that I would like to store as a string. I can do this as follows:
byte[] array = new byte[] { 0x01, 0x02, 0x03, 0x04 };
string s = System.BitConverter.ToString(array);
// Result: s = "01-02-03-04"
到目前为止好。有谁知道我是怎么把它恢复到一个数组?有没有过载(中BitConverter.GetBytes),它接受一个字符串,它似乎是一个讨厌的解决办法,打破字符串转换成字符串数组,然后转换成他们中的每
So far so good. Does anyone know how I get this back to an array? There is no overload of BitConverter.GetBytes() that takes a string, and it seems like a nasty workaround to break the string into an array of strings and then convert each of them.
所讨论的阵列可以是可变长的,大概20个字节。
The array in question may be of variable length, probably about 20 bytes.
推荐答案
不是一个内置的方法,而是一种实现。 (它可以在不拆分虽然做)。
Not a built in method, but an implementation. (It could be done without the split though).
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);
不拆分方法:(让许多的假设字符串格式)
Method without Split: (Makes many assumptions about string format)
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);
和一个方法,没有任何拆分或子。你可能会出手,如果你犯这个源代码控制,但。我认为这样的健康问题概不负责。
And one more method, without either split or substrings. You may get shot if you commit this to source control though. I take no responsibility for such health problems.
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转换)
(basically implementing base16 conversion on two chars)
这篇关于BitConverter.ToString()反向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!