Last active
May 18, 2016 01:44
-
-
Save infusion/85dac25265a436feaf30 to your computer and use it in GitHub Desktop.
Small snippets to hack double values in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copyright (c) 2016, Robert Eisele ([email protected]) | |
* 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; | |
}; | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copyright (c) 2016, Robert Eisele ([email protected]) | |
* 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