将二进制代码保存到文件

时间:2015-12-07 13:09:39

标签: c# encoding binary

我有一个只包含10的字符串,我需要将其保存为.txt文件。
我也希望它尽可能小。由于我有二进制代码,我可以把它变成几乎所有东西。将其保存为二进制不是一种选择,因为显然每个字符都是一个完整的字节,即使它是10。 我想过将我的字符串转换为字节数组但是尝试将"11111111"转换为Byte给了我一个System.OverflowException。 我的下一个想法是使用ASCII代码页或其他东西。但我不知道那是多么可靠。或者,我可以将我的所有8位字符串转换为相应的数字。 8个字符最多变成3(255),这对我来说似乎很不错。因为我知道最高的个人数字是255,所以我甚至不需要任何分隔符来解码。
但我确信这是一种更好的方法 所以:
存储仅包含10的字符串的最佳/最有效方法究竟是什么?

2 个答案:

答案 0 :(得分:2)

您可以将所有数据表示为64位整数,然后将它们写入二进制文件:

// The string we are working with.
string str = @"1010101010010100010101101";
// The number of bits in a 64 bit integer!
int size = 64;
// Pad the end of the string with zeros so the length of the string is divisible by 64.
str += new string('0', str.Length % size);
// Convert each 64 character segment into a 64 bit integer.
long[] binary = new long[str.Length / size]
    .Select((x, idx) => Convert.ToInt64(str.Substring(idx * size, size), 2)).ToArray();
// Copy the result to a byte array.
byte[] bytes = new byte[binary.Length * sizeof(long)];
Buffer.BlockCopy(binary, 0, bytes, 0, bytes.Length);
// Write the result to file.
File.WriteAllBytes("MyFile.bin", bytes);

修改

如果你只是写64位,那么它就是一个单行:

File.WriteAllBytes("MyFile.bin", BitConverter.GetBytes(Convert.ToUInt64(str, 2)));

答案 1 :(得分:1)

我建议使用BinaryWriter。像这样:

BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create));