I have a BinaryStream class in JavasScipt that reads bytes from an array downloaded via XMLHHttpRequest and has the function next() which returns an unsigned byte (technically an integer). I need to read a double from the stream which is basically the same as DataStream.readDouble() from Java which uses the method Double.longBitsToDouble(long). I can't figure out how the longBitsToDouble method works.
This is the the code I have:
var bits = stream.nextLong();
if (bits == 0x7ff0000000000000)
this.variables = [Infinity];
else if (bits == 0xfff0000000000000)
this.variables = [-Infinity];
else if (bits >= 0x7ff0000000000001 && bits <= 0x7fffffffffffffff || bits >= 0xfff0000000000001 && bits <= 0xfff0000000000001)
this.variables = [NaN];
else
{
var s = ((bits >> 63) == 0) ? 1 : -1;
var e = ((bits >> 52) & 0x7ff);
this.variables = [(e == 0) ? (bits & 0xfffffffffffff) << 1 : (bits & 0xfffffffffffff) | 0x10000000000000];
// This must be incorrect because it returns a number many times higher than it should
}
console.log(this.variables[0]);
I found a JavaScript library that can encode and decode many different types of numbers from an array of bytes here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With