【问题标题】:Converting binary data to bytes in c#在c#中将二进制数据转换为字节
【发布时间】:2012-03-14 23:37:20
【问题描述】:

我们有一个包含二进制值的文本文件。 比如说,我们有一个文件“file.txt”,它包含二进制数据,比如 11001010 该文件的大小为 8 字节。 但我们希望这些 8 字节 被读取为位,即 8 位,从而将 8 位转换为 1 个字节。我们该怎么做? 我们只知道程序: 1.取一个缓冲区并将单个值读入缓冲区 2.如果缓冲区值达到8,则将这8位转换为一个字节并写入文件。

提前致谢。

【问题讨论】:

  • 我们不知道从哪里开始。我们也尝试将其命名为“file.bin”,但没有用
  • @Henk,他说文件包含 0 和 1。
  • @RoyDictus :是的,更像'0''1'

标签: c# bytearray bitarray


【解决方案1】:

给定一个字符串,我怀疑你想要Convert.ToByte(text, 2);

对于不止一个字节,我认为没有内置任何东西可以将长字符串转换为这样的字节数组,但如果需要,您可以重复使用Substring

【讨论】:

  • @Timwi:因为我没有喝足够的咖啡。谢谢,已修复。
【解决方案2】:

以下代码读取您描述的这样一个文本文件。如果文件包含多个不能被 8 整除的二进制数字,则无关的数字将被丢弃。

using (var fileToReadFrom = File.OpenRead(@"..."))
using (var fileToWriteTo = File.OpenWrite(@"..."))
{
    var s = "";
    while (true)
    {
        var byteRead = fileToReadFrom.ReadByte();
        if (byteRead == -1)
            break;
        if (byteRead != '0' && byteRead != '1')
        {
            // If you want to throw on unexpected characters...
            throw new InvalidDataException(@"The file contains a character other than 0 or 1.");
            // If you want to ignore all characters except binary digits...
            continue;
        }
        s += (char) byteRead;
        if (s.Length == 8)
        {
            fileToWriteTo.WriteByte(Convert.ToByte(s, 2));
            s = "";
        }
    }
}

【讨论】:

    【解决方案3】:

    以防万一我们谈论的是字节而不是字符:

            byte output;
            using (var inFile = File.OpenRead("source"))
            {
                int offset = 0;
                var data = new byte[8];
                while (inFile.Read(data, offset, 8) == 8)
                {
                    output = (byte)(data[0] << 7);
                    output += (byte)(data[1] << 6);
                    output += (byte)(data[2] << 5);
                    output += (byte)(data[3] << 4);
                    output += (byte)(data[4] << 3);
                    output += (byte)(data[5] << 2);
                    output += (byte)(data[6] << 1);
                    output += (byte)data[7];
    
                    offset += 8;
    
                    // write your output byte
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 2017-11-22
      • 2015-08-05
      • 2012-07-16
      • 1970-01-01
      • 2014-03-29
      • 2013-03-06
      相关资源
      最近更新 更多