Skip to content

Instantly share code, notes, and snippets.

@dy
Last active December 27, 2024 18:09
Show Gist options
  • Save dy/d661e5282b33aee21c475852af9a954b to your computer and use it in GitHub Desktop.
Save dy/d661e5282b33aee21c475852af9a954b to your computer and use it in GitHub Desktop.
Construct float from sign, exponent, significand ints
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