Last active
December 27, 2024 18:09
-
-
Save dy/d661e5282b33aee21c475852af9a954b to your computer and use it in GitHub Desktop.
Construct float from sign, exponent, significand ints
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
function constructFloat64(sign, exp, sig) { | |
// Constants | |
const EXPONENT_BIAS = 1023n; | |
const EXPONENT_MASK = 0x7FFn; | |
const SIGNIFICAND_MASK = 0xFFFFFFFFFFFFFn; | |
console.log(sign, exp, sig, BigInt(sig) & SIGNIFICAND_MASK) | |
// Mask and adjust the components | |
sign = sign < 0 ? 1n : 0n; | |
exp = (BigInt(exp) + EXPONENT_BIAS) & EXPONENT_MASK; // Apply bias and mask to 11 bits | |
sig = BigInt(sig) & SIGNIFICAND_MASK; // Mask to 52 bits | |
// Combine the parts into a 64-bit value | |
const bits = (sign << 63n) | (exp << 52n) | sig; | |
// Convert the 64-bit value to a Float64Array | |
const buffer = new ArrayBuffer(8); | |
const view = new DataView(buffer); | |
view.setBigUint64(0, bits); | |
// Return the float value | |
return view.getFloat64(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment