Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Big Endian float conversion

Status
Not open for further replies.

piote

Programmer
Aug 26, 2007
4
PL
Hi,
I am trying to convert a Big Endian data file to something readable on most Windows PCs. I do ok with integer data but I cannot convert the floating points (32-bit IEEE).
1) Is it possible for a BinaryReader to account for Big Endian, such that .ReadSingle() would return the correct value?

2) If I have to read the bytes one at a time and reverse them, is there a way to type cast it to a float?

I pursued #2 for a while, but C# type-casting seems to convert the actual value and not the binary that represents it. So the result is something like 1.12E9 instead of 89.9.
I really don't know how to make it work correctly. I would be grateful for any help.

Regards,
Piote
 
I do not know about #1, but for #2, manually tweaking the byte order is the only way to go to convert big-endian ints to little-endian. Here's how I do it using a struct, which works well for 4-byte numeric types, including float. (Note that you can also use the BitConverter.ToSingle() which takes a byte array.)
Code:
[StructLayout(LayoutKind.Explicit)]
struct UnionInt
{
	[FieldOffset(0)] public byte byte0;
	[FieldOffset(1)] public byte byte1;
	[FieldOffset(2)] public byte byte2;
	[FieldOffset(3)] public byte byte3;

	[FieldOffset(0)] public float AsSingle;
	[FieldOffset(0)] public int AsInt32;

	public void FromBigEndian(byte[] bigEndianData)
	{
		this.byte0 = bigEndianData[3];
		this.byte1 = bigEndianData[2];
		this.byte2 = bigEndianData[1];
		this.byte3 = bigEndianData[0];
	}
}
Here's how to use it...
Code:
[COLOR=green]// Simulate big endian.[/color]
byte[] b = new byte[] {0x42, 0xb3, 0xcc, 0xcd};
float bf = BitConverter.ToSingle(b, 0);
MessageBox.Show(string.Format("big endian data = {0}", bf));

[COLOR=green]// Convert to little endian. Output is 89.9[/color]
UnionInt val = new UnionInt();
val.FromBigEndian(b);
MessageBox.Show("val = " + val.AsSingle.ToString());
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top