Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.Double.longBitsToDouble function in JavaScript

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]);
like image 252
trumank Avatar asked Nov 05 '22 12:11

trumank


1 Answers

I found a JavaScript library that can encode and decode many different types of numbers from an array of bytes here.

like image 124
trumank Avatar answered Nov 15 '22 01:11

trumank