-1

I have unsigned 32-bit, 64-bit primitives that are stored as bytes. I need to use them in Java. So I thought build them back together from bytes. First I'm playing with random bytes to make sure everything is calculated correctly. But I've encountered some problems:

// input: array of 4 bytes (unsigned int 0 to 4,294,967,295)
// output: double 0.0 to 1.0 (0 -> 0.0, 2,147,483,647 ~> 0.5, 4,294,967,295 -> 1.0)

byte[] bytes = new byte[100];
(new Random()).nextBytes(bytes); // randomize bytes

long a = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | bytes[0];
double b = 1.0 * (a & 0xffffffffL) / 0xffffffffL;

System.out.println(bytes[3] + "," + bytes[2] + "," + bytes[1] + "," + bytes[0]);
System.out.println(a);
System.out.println(b);

The output b is most of the time near 1.0 and a near max unsigned int. What am I doing wrong ? How do I get the wanted behavior ? And how do I do the same (correct calculation) with 8 bytes for QWORD ?

Bitterblue
  • 13,162
  • 17
  • 86
  • 124

1 Answers1

1

To convert a byte array to a double, use a ByteBuffer, see this question for example code. As you'll note in the example code, you may need to change the endian order of the byte array if the output and input platforms don't match.

Community
  • 1
  • 1
Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • That will simplify loading the long, but won't convert it to double. – Hot Licks Apr 15 '13 at 15:18
  • Was wasn't clear on if the byte array was a long or a double; if it's a long, then the easiest way to convert it to a double is `long lng = byteBuffer.getLong(); double d = 1.0 * lng;` – Zim-Zam O'Pootertoot Apr 15 '13 at 15:20
  • Is there a correct way to extract ints and longs with a basic byte array ? My existing code is very complex already and I need the most performance I can get. – Bitterblue Apr 15 '13 at 15:37
  • For `byte[] bytearray` you would use `int i = ByteBuffer.wrap(bytearray).getInt()` and `long l = ByteBuffer.wrap(bytearray).getLong()`, assuming the byte/bit ordering is the same on the platform that produced `bytearray` and the platform that is parsing `bytearray`. You'll know immediately if the bit/byte ordering is wrong when you test the code; at that point you'll either need to read the platform documentation to determine the correct bit/byte ordering, or else you'll need to just play around with the ordering until it comes out right. – Zim-Zam O'Pootertoot Apr 15 '13 at 15:39