This discussion is archived
6 Replies Latest reply: Sep 6, 2013 5:03 PM by jschellSomeoneStoleMyAlias RSS

How to read  and convert single precision 32 bit float (IEEE754) from a stream

4e879444-6514-4836-b150-1425e3896248 Newbie
Currently Being Moderated

I am reading single precision 32 bit float (IEEE754) from a stream and I stored the values in a byte array. I want to convert that float value to everyday numbers so that I can do calculations (adding, finding out standard deviation, etc.). The numerical values are 10 to 11 digits long, so I am thinking to use "long" type. (Should I use bigInteger?). Anyway my problem is should I use getFloat(index) or getInt(index)? Both read 4 bytes, only the return values are either int or float. I will then have to convert the values into long, keeping in mind that it is IEEE754  single precision 32 bit float, in little endian byte order.

 

So far, through web search, I have cobbled up these:

[Code]

FileInputStream fis = new FileInputStream(file); 

DataInputStream dis = new DataInputStream(fis); 

byte[] bs = new byte[appropriate_size]; 

dis.read(bs);

 

ByteBuffer b = ByteBuffer.wrap(bs).order(ByteOrder.LITTLE_ENDIAN);

for (int i = 0; i < bs.length; i+=4){

    Float f = b.getFloat(i);

    //convert that float value and save in an array

   data[some_index] = converted_value;

}

[/Code]

Questions:

(0)  Should I use getFloat(index) or getInt(index)?

(1) Is the loop statement correct? My understanding is 4 bytes is a "single" piece of data I am interested in, the one I need to convert to a large decimal number ("long" type)

Suspicion: my loop is controlled by byte array (bs), but I am reading from byteBuffer (b)..... is it right?

 

(2) How do I convert the float value to appropriate decimal value and then convert to long?

I found "floatToIntBits(float)" method, which, as per Oracle API, "returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout..."

Isn't it what I want? I am asking to all of you as well as to myself.

I should have known better, but I am confused.

Reason: I used a hex editor to "see" what is going on in the float area. It showed hex strings, and the numerical value was the same as that of output from the floatToIntBits method.

(The hex editor has big/little endian toggle, and "little endian" was selected.) How could they have the same output? The i.Hex did not mention anything about IEEE754 32 bit single precision float.


Also, I found an online hex/IEEE754 float converter, and the output was different. hence the confusion.

 

The hex string sequences I saw in the hex editor is like 012A5F4E B4F2454E 926A5F4E...

 

Dear gurus, what would be appropriate conversion of, let's say, the first one (012A5F4E)?

 

Please give some guidance. Thank you.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points