Skip to content

Instantly share code, notes, and snippets.

@wjw12
Last active October 21, 2022 03:21
Show Gist options
  • Select an option

  • Save wjw12/12d43e578fb63208af898019b3d513f9 to your computer and use it in GitHub Desktop.

Select an option

Save wjw12/12d43e578fb63208af898019b3d513f9 to your computer and use it in GitHub Desktop.
fp64_to_float
// input cannot be larger the 2^31
// this should allow at least 6 digits precision in the fractional part
// https://stackoverflow.com/questions/45929493/node-js-maximum-safe-floating-point-number
function fp64_to_float(a) {
// avoid large number
let mask = BigInt("0xffffffff000000000000000000000000")
if ((a & mask) != 0n) {
throw new Error("too large")
}
// integer part
mask = BigInt("0x10000000000000000")
let base = 1
let result = 0
for (let i = 0; i < 32; ++i) {
if ((a & mask) != 0n) { result += base }
base *= 2
mask = mask << 1n
}
// fractional part
mask = BigInt("0x8000000000000000")
base = 0.5
for (let i = 0; i < 32; ++i) {
if ((a & mask) != 0n) { result += base }
base /= 2
mask = mask >> 1n
}
console.log(result)
}
fp64_to_float(BigInt("9223372023969873920")) // 0.5
fp64_to_float(BigInt("36893488147419103232")) // 2.0
fp64_to_float(BigInt("25744505231652237576")) // 1.395612
fp64_to_float(BigInt("13217669704916664320")) // 0.716531
fp64_to_float(BigInt("1") << 95n) // 2147483648
fp64_to_float(BigInt("1") << 96n) // error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment