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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

convert array of bytes to int or float

Status
Not open for further replies.

mcklsn

Programmer
Mar 16, 2003
40
US
How do you convert an array of bytes to an int or a float?. I'm reading in binary bytes of data from a file. I have to take them 4 at a time, reverse their order (because they come in "wrong endian"), and then combine them into a single int or a single float. I know how to do everything but that last step. Any help would be appreciated.
 
you should use Convert.toInteger(array);
or Integer.parse...
or convert it to string then to integer
 
Thanks
I have a more complicated problem than I thought. I have 4 byte (32 bit) floating point numbers in a file with the 4 bytes in the wrong order. I can read each byte into an int32, then, by shifting them the appropriate number of places, OR them all together to form a single int32 with the bit pattern for the float in it. I then need to have C# recognize this int32 as a float, NOT convert it to a float. If it converts it, then the 32-bit pattern is assumed to be an integer and the integer value is converted to a float. This is not what I need.
This is easy to do in Java using the Float.IntBitsToFloat method, but there is no equivalent method in .Net. Does anybody know how the do this in C#?
Thanks
 
Instead of reading them into an int, read them into a byte array. You can put them into the byte array in the correct order and then convert the byte array into whatever data type you need:
Code:
byte[] input = new byte[4]; // 32-bit byte array

// put your bytes into the array in correct order

float f = BitConverter.ToSingle( input, 0 );
If you must use an int to read them in, just change the first line to:
Code:
byte[] input = BitConverter.GetBytes( /* your int here */ );
Let us know if that helps.
 
Thanks a lot. That did the trick. I appreciate the help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top