Hi,

So you have been driving yourself crazy looking over the Internet on how to do those bloody conversions from a

double

to a

byte[]

array using << or <<< and god knows what else in Java?

Well you have come to the right place.

This function takes a double as argument and converts it to an 8-Byte array in Big Endian format. Alternatively, you can use the Little Endian format by uncommenting the 2nd line. For more information on Endianess you can check http://en.wikipedia.org/wiki/Endianness

public static byte[] doubleToByteArray(double valToConv) {
  ByteBuffer bb = ByteBuffer.allocate(8);
  //bb.order(ByteOrder.LITTLE_ENDIAN);
  bb.putDouble(valToConv);
  bb.flip();
  byte[] bbb= new byte[8];
  bb.get(bbb, 0, 8);
  return bbb;
}

This method takes an 8-Byte Array in Big Endian and transforms it back to a Double.

public static double byteArrayToDouble(byte[] arrayToConv) {
  ByteBuffer bb = ByteBuffer.allocate(byteArrayToConv.length);
  //bb.order(ByteOrder.LITTLE_ENDIAN);
  bb.put(byteArrayToConv);
  bb.flip();
  return bb.getDouble();
}

As a final note, if you look at the Java API you will find many more methods in the ByteBuffer Class to handle conversions to Byte Arrays, like from Int, Long, etc...

Enjoy,

3 comments

Comment from: Wookai [Visitor] · http://20-100.ch/blog
ByteBuffer is one of those "unknown" Java classes that developers tend to re-invent all day long and which could save us a lot of time and trouble !

Thanks for documenting it !

PS: love your var names, very... meaningful ;) !
03/06/08 @ 10:24
Comment from: Trefex [Member]
LMAO.

Look on the other Blog. I explain that right now I just dump my code.
When I found the plugins and themes that I want, I will update the posts.

If I don't put it down directly, I will forget again :D
03/06/08 @ 11:33
Comment from: DidouPh [Visitor] · http://matoilnet.com
haha read the code aloud ... hilarious
03/07/08 @ 00:52

This post has 1 feedback awaiting moderation...

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)