Skip to content

Instantly share code, notes, and snippets.

@infusion
Last active May 18, 2016 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save infusion/85dac25265a436feaf30 to your computer and use it in GitHub Desktop.
Save infusion/85dac25265a436feaf30 to your computer and use it in GitHub Desktop.
Small snippets to hack double values in JavaScript
/**
* Copyright (c) 2016, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
**/
// Converts a JavaScript double number to a node Buffer
var DoubleToBuffer = (function() {
var FLOAT = new Float64Array(1)
return function(x) {
FLOAT[0] = x;
var buffer = new Buffer(FLOAT.buffer.byteLength);
var bytes = new Uint8Array(FLOAT.buffer);
for (var i = 0; i < buffer.length; i++) {
buffer[i] = bytes[i];
}
return buffer;
};
})();
/**
* Copyright (c) 2016, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
**/
// Extracts the exponent of a double value x
var getExponent = (function() {
var FLOAT = new Float64Array(1)
var INT = new Uint32Array(FLOAT.buffer)
var MIN_DENORM = Math.pow(2, -1023)
return function(x) {
FLOAT[0] = x;
INT[0] = 0;
INT[1] &= ~((1 << 20) - 1);
return FLOAT[0] || MIN_DENORM;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment