|
-
Dec 17th, 2009, 04:06 AM
#1
Reading 2 bytes together
Hi,
I am reading a file into byte array and consists of header information.
The format specs say that the first 2 bytes gives you a static value of 474. Right now I am converting the bytes (necessarily numeric values) into binary format (representing them as strings), append the first 2 bytes together and then convert it into integer again.
That's working, but I just wanted to make sure if there is any other way to read more than 1 byte together and display the result.
Or any other way, instead of reading into byte array, something long that line?
Thank you
-
Dec 17th, 2009, 05:02 AM
#2
Re: Reading 2 bytes together
Code:
byte[] data = File.ReadAllBytes("file path here");
short header = BitConverter.ToInt16(data, 0);
if (header == 474)
{
// Valid file.
}
-
Dec 18th, 2009, 05:13 AM
#3
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?
-
Dec 18th, 2009, 10:16 PM
#4
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. }
-
Dec 27th, 2009, 11:14 AM
#5
Hyperactive Member
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:
Last edited by Arrow_Raider; Dec 29th, 2009 at 12:34 PM.
My monkey wearing the fedora points and laughs at you.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|