Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a byte array into a double and back?

For converting a byte array to a double I found this:

//convert 8 byte array to double int start=0;//??? int i = 0;     int len = 8;     int cnt = 0;     byte[] tmp = new byte[len];     for (i = start; i < (start + len); i++) {         tmp[cnt] = arr[i];         //System.out.println(java.lang.Byte.toString(arr[i]) + " " + i);         cnt++;     }     long accum = 0;     i = 0;     for ( int shiftBy = 0; shiftBy < 64; shiftBy += 8 ) {         accum |= ( (long)( tmp[i] & 0xff ) ) << shiftBy;         i++;     }          return Double.longBitsToDouble(accum); 

But I could not find anything which would convert a double into a byte array.

like image 412
Octavian Avatar asked May 25 '10 14:05

Octavian


People also ask

Can a byte be cast to a double?

You can not cast from a double to byte because the byte has a range smaller than the double and it does not contain decimals like a double does.

Can you cast a byte object to a double value?

No, an object cannot be cast to a primitive value.

Can we convert byte array to file in Java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.


1 Answers

Or even simpler,

import java.nio.ByteBuffer;  public static byte[] toByteArray(double value) {     byte[] bytes = new byte[8];     ByteBuffer.wrap(bytes).putDouble(value);     return bytes; }  public static double toDouble(byte[] bytes) {     return ByteBuffer.wrap(bytes).getDouble(); } 
like image 112
usethe4ce Avatar answered Oct 07 '22 01:10

usethe4ce