Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Decode 32/64-bit float from bytes in JavaScript

View decodeFloat.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
// Derived from http://stackoverflow.com/a/8545403/106786
function decodeFloat(bytes, signBits, exponentBits, fractionBits, eMin, eMax, littleEndian) {
var totalBits = (signBits + exponentBits + fractionBits);
 
var binary = "";
for (var i = 0, l = bytes.length; i < l; i++) {
var bits = bytes[i].toString(2);
while (bits.length < 8)
bits = "0" + bits;
 
if (littleEndian)
binary = bits + binary;
else
binary += bits;
}
 
var sign = (binary.charAt(0) == '1')?-1:1;
var exponent = parseInt(binary.substr(signBits, exponentBits), 2) - eMax;
var significandBase = binary.substr(signBits + exponentBits, fractionBits);
var significandBin = '1'+significandBase;
var i = 0;
var val = 1;
var significand = 0;
 
if (exponent == -eMax) {
if (significandBase.indexOf('1') == -1)
return 0;
else {
exponent = eMin;
significandBin = '0'+significandBase;
}
}
 
while (i < significandBin.length) {
significand += val * parseInt(significandBin.charAt(i));
val = val / 2;
i++;
}
 
return sign * significand * Math.pow(2, exponent);
}
 
// Sample usage
ReadSingle: function () {
var bytes = this.ReadBytes(4);
return this.$decodeFloat(bytes, 1, 8, 23, -126, 127, true);
},
ReadDouble: function () {
var bytes = this.ReadBytes(8);
return this.$decodeFloat(bytes, 1, 11, 52, -1022, 1023, true);
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.