【问题标题】:Most efficient way to save binary code to file将二进制代码保存到文件的最有效方法
【发布时间】:2015-12-07 13:09:38
【问题描述】:

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

【问题讨论】:

  • 我会看看base64
  • @Shnugo base64 倾向于使数据更大,而不是更小。
  • 为什么不让它成为比特?所以字符串10011001(磁盘上的8个字节)将变成0x99(磁盘上的1个字节)。然后,使用 ZIP 进一步压缩它。
  • "I could turn all of the 8-Bit pieces of my string into the corresponding numbers." - 如果您想获得真正的创意,您甚至可以将 整个字符串 存储为单个数字(然后是另一个数字作为长度),仅此而已。
  • “我需要将它保存到 .txt 文件中。”你真的需要它是文本吗?如果是这样,您对使用的字符有什么限制 - 以及哪种编码?您声称“不能将其保存为二进制文件,因为显然每个字符都是一个完整的字节,即使它是 1 或 0。” - 这不是真的,因为您可以创建一个字节数组,其中每个字节都来自 8 个输入位...

标签: c# encoding binary


【解决方案1】:

您可以将所有数据表示为 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)));

【讨论】:

  • 实际上有争议的是,最好将此方法与字节一起使用而不是 long,因为这样可以在长度小于 64 的字符串上节省更多空间!
  • 那不是很好。 "1111111111111111111111111111111111111111111111111111111111111111111111111111111" 8 字节大,完美。
  • 酷 - 如果你只写 64 位,请查看我的编辑 - 它可以是单行的。
【解决方案2】:

我建议使用BinaryWriter。像这样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 2018-11-13
    • 1970-01-01
    相关资源
    最近更新 更多