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 ?