How to read a float from a Big Endian binary file.  
Author Message
jim rozak





PostPosted: Visual C# Language, How to read a float from a Big Endian binary file. Top

I have a binary file written in big endian. Scattered within the binary file, there are 4-byte floats that I wish to read. I can't use methods like ReadSingle() since it is in big endian format. The only thing I have found to solve this is to read it in one byte at a time...reverse the order of the array...write it out using BinaryWriter and read it back using BinaryReader.ReadSingle() from the temp file. This seems to have a lot of over head...is there a better way to do this (I tried the way below but did not work)

Thanks. -JRozak

FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);BinaryReader r = new BinaryReader(fs);

float x=(float)IPAddress.NetworkToHostOrder(r.ReadUInt32());



Visual C#2  
 
 
Mike Danes





PostPosted: Visual C# Language, How to read a float from a Big Endian binary file. Top

One possible solution:

BinaryReader reader = new BinaryReader(stream);

// read 4 bytes

byte[] floatBytes = reader.ReadBytes(4);

// swap the bytes

byte temp = floatBytes[0];

floatBytes[0] = floatBytes[3];

floatBytes[3] = temp;

temp = floatBytes[1];

floatBytes[1] = floatBytes[2];

floatBytes[2] = temp;

// get the float from the byte array

float value = BitConverter.ToSingle(floatBytes, 0);

Console.WriteLine(value);


 
 
James Curran





PostPosted: Visual C# Language, How to read a float from a Big Endian binary file. Top

Same concept, a bit simpler:



BinaryReader reader = new BinaryReader(stream);
// read 4 bytes
byte[] floatBytes = reader.ReadBytes(4);
// swap the bytes
floatBytes=Array.Reverse(floatBytes);
// get the float from the byte array
float value = BitConverter.ToSingle(floatBytes, 0);



 
 
jim rozak





PostPosted: Visual C# Language, How to read a float from a Big Endian binary file. Top

Thanks however when I get a compile error.

Cannot implicitly convert type 'void' to 'byte[]' For the floatBytes=Array.Reverse(floatBytes); statement. I don't know why


 
 
Paul Louth





PostPosted: Visual C# Language, How to read a float from a Big Endian binary file. Top

Just change it to:

Array.Reverse(floatBytes);


 
 
jim rozak





PostPosted: Visual C# Language, How to read a float from a Big Endian binary file. Top

Thanks...I just tried that and it worked...so I was about to post it. Thanks again.
 
 
Paul Louth





PostPosted: Visual C# Language, How to read a float from a Big Endian binary file. Top

No problem. Glad it's working. :o)
 
 
James Curran





PostPosted: Visual C# Language, How to read a float from a Big Endian binary file. Top

Cannot implicitly convert type 'void' to 'byte[]' For the floatBytes=Array.Reverse(floatBytes); statement. I don't know why

Sorry about that. I had just recently written the same code for my own project, so I thought I could recreate it from memory.