Skip to content

Instantly share code, notes, and snippets.

@barretlee
Created September 27, 2016 15:59
Show Gist options
  • Save barretlee/f8227c1bce1570121ea25964e299557d to your computer and use it in GitHub Desktop.
Save barretlee/f8227c1bce1570121ea25964e299557d to your computer and use it in GitHub Desktop.
double-bits
const db = require('double-bits');
const pad = require('pad');
// [lo, hi] where lo is a 32 bit integer and hi is a 20 bit integer.
const base2Str = (n) => {
const f = db.fraction(n);
const s = db.sign(n) ? '-' : '';
const e = `2^${db.exponent(n) + 1}`;
const t = `0.${pad(f[1].toString(2), 20, '0')}${pad(f[0].toString(2), 32, '0')}`;
return `${s}${e} * ${t}`;
};
console.log(base2Str(0.1).toString(2));
console.log(base2Str(0.2).toString(2));
console.log(base2Str(0.3).toString(2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment