2011-05-16 43 views
1

可能重复:
Read hex in C# using IOC#一次读取文件作为十六进制的一个字节

嗨,我是新来从Java C#和我一直停留在过去两年几小时的东西很简单,或者应该是这样的想知道如果有人会帮助我请:) :)

在Java中,我使用代码beleow在文件中读取,它使用十六进制读取给定的文件,一次一个字节?什么是在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); 
    } 
} 

很抱歉,如果这似乎达姆我只是卡住了!提前谢谢了!

:)

+0

尝试[这](http://stackoverflow.com/questions/5608824/read-己在-C-使用1-10)。 – jacknad 2011-05-16 01:39:39

回答

5

试试这个,这是从您发布的代码挺的笔直转换:

 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; 

      } 
     } 
+2

您可以使用格式字符串X2强制2位数字,而不是预先置零。 – Josh 2011-05-16 01:45:00

+1

和格式是这样完成的:string hex = String.Format(“{0:X2}”,hexIn); – 2013-11-08 02:50:43

相关问题