显示外部的二进制代码 files/program

Show binary code of external files/program

无论如何,所有数字数据都存储在0和1中。我猜这就是二进制数据的原理。

有没有一种方法或程序包可以向您显示 file/single-exe-program 的二进制代码,说明它实际上是如何以 0/1 格式存储的??

我会这样看: - 导入某个随机文件 - 将其转换为 0/1 格式 - 将 1/0 数据存储在 txt 中 (streamwriter/binarywriter)

如果是,这是否适用于任何 .NET 语言(首选:c#)?

基本上你只需要把它分成两步:

  1. 将文件转换为字节
  2. 将一个字节转换为二进制字符串

The first step is easy:

var fileBytes = File.ReadAllBytes(someFileName);

第二步就不那么直接了,but still pretty easy:

var byteString = string.Concat(fileBytes.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')))

这里的想法是你 select 每个字节单独,将每个字节转换为二进制字符串(向左填充,所以每个字节都是 8 个字符,因为许多字节都有前导零),然后连接所有这些成一个字符串。 (在下面@xanatos 的部分评论中提供。)

您可以用二进制模式打开文件。没有测试它,但它应该可以工作:

BitArray GetBits(string fuleSrc)
{
     byte[] bytesFile;
     using (FileStream file = new FileStream(fuleSrc, FileMode.Open, FileAccess.Read))
     {
          bytesFile = new byte[file.Length];
          file.Read(bytes, 0, (int)file.Length);
     }

     return new BitArray(bytesFile);
}

我认为这就是您要找的东西:

byte [] contents = File.ReadAllBytes(filePath);
StringBuilder builder = new StringBuilder();
for(int i = 0; i<contents .Length; i++)
{
  builder.Append( Convert.ToString(contents[i], 2).PadLeft(8, '0') );
}

现在,您可以将 builder 内容写入文本文件。

使用 FileStreamStreamWriterStringBuilderConvert

的解决方案
static void Main(string[] args)
{
    StringBuilder sb = new StringBuilder();
    using (FileStream fs = new FileStream(InputFILEPATH, FileMode.Open))
    {
          while (fs.Position != fs.Length)
          {
              sb.Append(Convert.ToString(fs.ReadByte(),2));
          }
    }
    using (StreamWriter stw = new StreamWriter(File.Open(OutputFILEPATH,FileMode.OpenOrCreate)))
    {
            stw.WriteLine(sb.ToString());
    }
   Console.ReadKey();
}

这将流式传输转换,如果您有大文件,这很有用。

using System;
using System.IO;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var buffer = new byte[1024];
            int pos = 0; 

            using (var fileIn = new FileStream(@"c:\test.txt", FileMode.Open, FileAccess.Read))
            using (var fileOut = new FileStream(@"c:\test.txt.binary", FileMode.Create, FileAccess.Write))
                while((pos = fileIn.Read(buffer,0,buffer.Length)) > 0)
                    foreach (var value in buffer.Take(pos).Select(x => Convert.ToString(x, 2).PadLeft(8, '0')))
                        fileOut.Write(value.Select(x => (byte)x).ToArray(), 0, 8);
        }
    }
}