39

I have a 4 bytes array which represent a float value. The bytes is read from network, for example, 3e 3f e3 a0. How can I convert it from byte[] to float in java?

2
  • 6
    Peters answer should be marked as accepted. Commented May 22, 2015 at 10:46
  • Should it? Peter's answer requires constructing an object while Xavier's doesn't. Commented Aug 1, 2017 at 20:03

3 Answers 3

87

In Java a char is 16-bit. If you mean you have a 4 byte values in little endian byte order which you need to convert to a float you can use ByteBuffer.

byte[] bytes = { }
float f = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
Sign up to request clarification or add additional context in comments.

3 Comments

Very useful class indeed.
There is also version with offset and length: ByteBuffer.wrap(bytes,offset,length)
The order! That did it for me.
9

Try this:

float foo = Float.intBitsToFloat( buffer[n] ^ buffer[n+1]<<8 ^ buffer[n+2]<<16 ^ buffer[n+3]<<24 );

1 Comment

XOR? Don't you mean OR?
0

it worked for me.

// {64, 46, -128} = 15.28
byte[] bt = {64, 46, -128};
ByteBuffer byteBuffer = ByteBuffer.allocate(8).put(bt);
byteBuffer.position(0);
Double d = byteBuffer.getDouble(); // 15.28

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.