如何将字符串如"01110100011001010111001101110100"转换为字节数组,然后使用File.WriteAllBytes,使得确切的二进制字符串是文件的二进制.在这种情况下,它将是文本"test".
Mac*_*ehl 35
如果您没有这种LINQ迷信,最近很常见,您可以尝试正常的方式
string input ....
int numOfBytes = input.Length / 8;
byte[] bytes = new byte[numOfBytes];
for(int i = 0; i < numOfBytes; ++i)
{
bytes[i] = Convert.ToByte(input.Substring(8 * i, 8), 2);
}
File.WriteAllBytes(fileName, bytes);
Run Code Online (Sandbox Code Playgroud)
LINQ很棒,但必须有一些限制.
Tho*_*que 10
您可以首先将字符串拆分为8个字符的字符串序列,然后将这些字符串转换为字节,最后将字节写入文件
string input = "01110100011001010111001101110100";
var bytesAsStrings =
input.Select((c, i) => new { Char = c, Index = i })
.GroupBy(x => x.Index / 8)
.Select(g => new string(g.Select(x => x.Char).ToArray()));
byte[] bytes = bytesAsStrings.Select(s => Convert.ToByte(s, 2)).ToArray();
File.WriteAllBytes(fileName, bytes);
Run Code Online (Sandbox Code Playgroud)
编辑:这是将字符串拆分为8个字符块的另一种方法,可能更简单一些:
int nBytes = (int)Math.Ceiling(input.Length / 8m);
var bytesAsStrings =
Enumerable.Range(0, nBytes)
.Select(i => input.Substring(8 * i, Math.Min(8, input.Length - 8 * i)));
Run Code Online (Sandbox Code Playgroud)
如果你知道字符串的长度是8的倍数,你可以使它更简单:
int nBytes = input.Length / 8;
var bytesAsStrings =
Enumerable.Range(0, nBytes)
.Select(i => input.Substring(8 * i, 8));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52389 次 |
| 最近记录: |