I'm new to C# moving from Java. I'm trying to read in a file using IO in HEX. When I read the first byte in I don't get what I'm seeing in my Hex editor.开发者_运维百科
I'm using
StreamReader reader = new StreamReader(fileDirectory);
int hexIn;
String hex;
for (int i = 0; (hexIn = reader.Read()) != -1; i++){
hex = Convert.ToString(hexIn, 16);
}
In Java I used
FileInputStream fis = new FileInputStream(file);
long length = file.length();
int hexIn;
String hex = "";
for(int i = 0; (hexIn = fis.read()) != -1; i++){
String s = Integer.toHexString(hexIn);
if(s.length() < 2){
s = "0" + Integer.toHexString(hexIn);
}
I hope this makes sense. Any help would be most apperciated :)
Thanks.
Don't use a StreamReader
—that's only for characters in a certain encoding (default UTF8). Use a FileStream
class instead:
FileStream fs = new FileStream(fileDirectory, FileMode.Open);
int hexIn;
String hex;
for (int i = 0; (hexIn = fs.ReadByte()) != -1; i++){
hex = string.Format("{0:X2}", hexIn);
}
You need such C#
code to achieve the same results as your Java code:
hex = hexIn.ToString("X").PadLeft(2, '0');
The Convert.ToString
also works, but IMO using the native ToString
of the integer is better practice.
Anyway you were missing the PadLeft
part that indeed caused 15 to be 'f' instead of 0F
.
精彩评论