Re: Reading 2 bytes together
Code:
byte[] data = File.ReadAllBytes("file path here");
short header = BitConverter.ToInt16(data, 0);
if (header == 474)
{
// Valid file.
}
Re: Reading 2 bytes together
Thanks JMC, didn't knew about the BitConverter class.
But, please correct me if I am wrong. How does BitConverter read the data off byte array? When I tried your code, it didn't give me the correct result. But when I swapped the bytes, it gave me correct result.
csharp Code:
byte[] data = System.IO.File.ReadAllBytes("rgbtest.jpg");
byte[] nb = new byte[2];
nb[0] = data[1];
nb[1] = data[0];
ushort magic = BitConverter.ToUInt16(nb, 0);
// swapping works
MessageBox.Show(string.Format("Magic Number: {0}", magic));
I tried to read a JPG file too, whose first byte is FF, second byte is D8, so 2 bytes must be FFD8 and Decimal equivalent is 65496, and I get this only when I swap the values.
What am I doing wrong?
Re: Reading 2 bytes together
I don't think you're doing anything wrong. I haven't really used the BitConverter all that much and I didn't take its endianness into account. It looks like it's little-endian, which makes sense, so you will, in fact, have to reverse the order of the bytes you want to test. Assuming .NET 3.5, LINQ can help you do that succinctly:
csharp Code:
byte[] data = File.ReadAllBytes("file path here");
short header = BitConverter.ToInt16(data.Take(2).Reverse().ToArray(), 0);
if (header == 474)
{
// Valid file.
}
Re: Reading 2 bytes together
This is how I would do it:
csharp Code:
string filename = "filename here";
FileStream fs = File.OpenRead(filename);
BinaryReader reader = new BinaryReader(fs);
byte[] magicBytes = reader.ReadBytes(2);
//474 in big endian is 0x01DA
if (magicBytes[0] == 0x01 && magicBytes[1] == 0xDA)
{
//yay
}
Make sure you put this in the using directives:
Of course, you also need to close the stream or the reader when you are done with it: