BitConverter.ToString()反过来?

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

byte[] array = new byte[] { 0x01, 0x02, 0x03, 0x04 }; string s = System.BitConverter.ToString(array); // Result: s = "01-02-03-04" 

到现在为止还挺好。 有谁知道我怎么回到arrays? BitConverter.GetBytes()没有超载,它接受一个字符串,这似乎是一个讨厌的解决方法,将字符串分解为字符串数组,然后转换它们中的每一个。

所讨论的arrays可以是可变长度的,可能大约20个字节。

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

 String[] arr=str.Split('-'); byte[] array=new byte[arr.Length]; for(int i=0; i 

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

 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); 

还有一种方法,没有分裂或子串。 如果你将它提交给源代码控制,你可能会被枪杀。 我对这些健康问题不承担任何责任。

 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转换)

你可以自己解析字符串:

 byte[] data = new byte[(s.Length + 1) / 3]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)( "0123456789ABCDEF".IndexOf(s[i * 3]) * 16 + "0123456789ABCDEF".IndexOf(s[i * 3 + 1]) ); } 

不过,我认为最好的解决方案是使用扩展:

 byte[] data = s.Split('-').Select(b => Convert.ToByte(b, 16)).ToArray(); 

如果您不需要该特定格式,请尝试使用Base64 ,如下所示:

 var bytes = new byte[] { 0x12, 0x34, 0x56 }; var base64 = Convert.ToBase64String(bytes); bytes = Convert.FromBase64String(base64); 

Base64也将大大缩短。

如果你需要使用那种格式,这显然无济于事。

 byte[] data = Array.ConvertAll(str.Split('-'), s => Convert.ToByte(s, 16)); 

我相信以下内容将有力地解决这个问题。

 public static byte[] HexStringToBytes(string s) { const string HEX_CHARS = "0123456789ABCDEF"; if (s.Length == 0) return new byte[0]; if ((s.Length + 1) % 3 != 0) throw new FormatException(); byte[] bytes = new byte[(s.Length + 1) / 3]; int state = 0; // 0 = expect first digit, 1 = expect second digit, 2 = expect hyphen int currentByte = 0; int x; int value = 0; foreach (char c in s) { switch (state) { case 0: x = HEX_CHARS.IndexOf(Char.ToUpperInvariant(c)); if (x == -1) throw new FormatException(); value = x << 4; state = 1; break; case 1: x = HEX_CHARS.IndexOf(Char.ToUpperInvariant(c)); if (x == -1) throw new FormatException(); bytes[currentByte++] = (byte)(value + x); state = 2; break; case 2: if (c != '-') throw new FormatException(); state = 0; break; } } return bytes; } 

将字符串分解为字符串数组然后转换每个字符串似乎是一个讨厌的解决方法。

我不认为还有另一种方式…… BitConverter.ToString生成的格式非常具体,所以如果没有现有方法将其解析回byte [],我想你必须自己做

ToString方法实际上不是用作转换,而是为调试提供人类可读的格式,易于打印输出等。
我重新考虑了byte [] – String – byte []的要求,可能更喜欢SLaks的Base64解决方案