2011-05-16 116 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

相關問題