【问题标题】:C# read file as hex one byte at a time [duplicate]C#将文件读取为十六进制,一次一个字节[重复]
【发布时间】:2011-08-26 03:04:53
【问题描述】:

可能重复:
Read hex in C# using IO

嗨,我是来自 Java 的 C# 新手,过去两个小时我一直被困在一些简单的事情上,或者应该想知道是否有人会帮助我 :)

在 Java 中,我使用下面的代码读取文件,它使用十六进制读取给定文件,一次一个字节?在 C# 中执行此操作的方法是什么?

int hexIn;

File file = new File(filePath);

FileInputStream fis = new FileInputStream(file);

 for(int i = 0; (hexIn = fis.read()) != -1; i++){

   String s = Integer.toHexString(hexIn);
   if(s.length() < 2){
     s = "0" + Integer.toHexString(hexIn);
    }
}

对不起,如果这看起来很愚蠢,我只是卡住了!非常感谢!

:)

【问题讨论】:

标签: c# file hex


【解决方案1】:

试试这个,它是您发布的代码的直接转换:

        using (var file = File.Open("p:\\t.txt", FileMode.Open))
        {
            int b;
            while ((b = file.ReadByte()) >= 0)
            {
                string s = b.ToString("X");
                if (s.Length < 2)
                    s = "0" + s;

            }
        }

【讨论】:

  • 您可以使用格式字符串 X2 来强制输入 2 位数字,而不是在前面加零。
  • 格式化是这样完成的:string hex = String.Format("{0:X2}", hexIn);
猜你喜欢
  • 2015-12-20
  • 2018-09-08
  • 1970-01-01
  • 2015-09-04
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 2011-08-04
  • 2013-04-30
相关资源
最近更新 更多