I have to read a binary file so I use this code:
static void ReadBin()
{
var sectors = new List<Sector>();
using (var b = new BinaryReader(File.Open("C:\\LOG.BIN", FileMode.Open)))
{
const int offset = 4096;
const int required = 2;
int pos = 0;
var length = (int)b.BaseStream.Length;
while (pos < length)
{
for (int i = 1; i <= 640; i++)
{
pos = (offset*i)-2;
b.BaseStream.Seek(pos, SeekOrigin.Begin);
// Read the next 2 bytes.
byte[] by = b.ReadBytes(required);
sectors.Add(new Sector { Number = i, Position = pos, Type = Sector.SetTypeFromExadecimalString(ByteArrayToString(@by)) });
pos = pos + 2;
}
}
}
}
As you can see the ByteArrayToString take the array of byte and write a string. The code of ByteArrayToString is:
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return string.Format("0x{0}", hex.ToString().ToUpper());
}
The machine that write the .bin file write it in LittleEndian. So following this StackOverflow thread "Is .NET BinaryReader always little-endian, even on big-endian systems?" I should be in "all" LittleEndian format (the ReadBytes and also the file generated by the machine). The problem is that the function ByteArrayToString() gives me this result: 0xF0FF that is in BigEndian and not in LittleEndian (infact I suppose that I should receive instead 0xFFF0), because after that I have to decode a lot of data and I can't be sure of the consistency of result (I have nothing to compare), I don't want to have problem to decode the .bin file, how can I achieve to obtaing 0xFFF0?
The endianness of BinaryReader
only affects methods such as ReadInt32
. It doesn't affect ReadBytes
- that will always return you the bytes in the order in which they occur within the stream.
If you need a byte array (or a hex representation of it) in a particular ordering, you'll have to perform that ordering yourself.
If the file is meant to already be in the endianness you want, then it may well be that you're simply reading the wrong data. I wouldn't be entirely surprised by this - you're repositioning the underlying stream, which the BinaryReader
may not be aware of. If it has read (say) 16 bytes into its buffer, it may not read from the stream again until you've read all of that buffer. I suggest you take BinaryReader
out of the equation and just use Stream
- it's not hard to write your own equivalent of ReadBytes
which simply loops until it's either run out of data or read all the data you need.
See more on this question at Stackoverflow