将二进制字符串表示形式转换为字节数组

如何将诸如“ 0111010001100101011100110111110100”之类的字符串转换为字节数组,然后使用File.WriteAllBytes使得确切的二进制字符串是文件的二进制文件。在这种情况下,它将是文本“ test”。



qq_遁去的一_1
浏览 1076回答 3
3回答

牛魔王的故事

如果您没有这种LINQ恋物癖,那么最近很常见,您可以尝试正常的方法string input ....int numOfBytes = input.Length / 8;byte[] bytes = new byte[numOfBytes];for(int i = 0; i < numOfBytes; ++i){&nbsp; &nbsp; bytes[i] = Convert.ToByte(input.Substring(8 * i, 8), 2);}File.WriteAllBytes(fileName, bytes);LINQ很棒,但是必须有一些限制。

梵蒂冈之花

有点晚了,但这是我的2美分:var binaryStr = "01110100011001010111001101110100";var byteArray = Enumerable.Range(0, int.MaxValue/8)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(i => i*8)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .TakeWhile(i => i < binaryStr.Length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(i => binaryStr.Substring(i, 8))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(s => Convert.ToByte(s, 2))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToArray();File.WriteAllBytes("C:\temp\test.txt", byteArray);
打开App,查看更多内容
随时随地看视频慕课网APP