Skip to content

Instantly share code, notes, and snippets.

@u840903
Last active November 10, 2021 05:50
Show Gist options
  • Save u840903/01c820922657dbe26ca7e2dc2839d55b to your computer and use it in GitHub Desktop.
Save u840903/01c820922657dbe26ca7e2dc2839d55b to your computer and use it in GitHub Desktop.
IEEE-754 Floating Point in Javascript
const pad = (str, n, a=0) => Array.from({length:n-str.length}).map(_ => a).join('') + str;
const nextPowerOf2 = (n) => Math.pow(2, Math.round(Math.max(n,0)).toString(2).length);
const getPowerOfTwoWindow = n => {
const next = nextPowerOf2(n);
return [next/2, next];
};
const floatToBinary = (n) => {
const sign = n > 0 ? 0 : 1;
const window = getPowerOfTwoWindow(n);
const windowStartAsPowersOfTwo = Math.log(window[0])/Math.log(2);
const exponent = 127 + windowStartAsPowersOfTwo;
const windowSize = window[1]-window[0];
const m = (N - windowSize)/windowSize;
const mantissa = Math.ceil(Math.pow(2, 23) * m);
const binary_sign = pad(sign.toString(2),1);
const binary_exponent = pad(exponent.toString(2),1);
const binary_mantissa = pad(mantissa.toString(2), 23);
return `${binary_sign}${binary_exponent}${binary_mantissa}`
};
const binaryToFloat = binary => {
const sign = binary.substring(0,1);
const exponent = binary.substring(1,9);
const mantissa = binary.substring(9,32);
const S = sign;
const E = parseInt(exponent,2);
const M = parseInt(mantissa, 2) /Math.pow(2,23);
// (-1)^S * (1 + M) * 2^(E-127)
return Math.pow(-1,S) * (1 + M) * Math.pow(2, E-127)
};
const N = 3.20;
const binary = floatToBinary(N);
const float = binaryToFloat(binary);
console.log('44, N -—>', N);
console.log('45, binary -—>', binary);
console.log('46, float -—>', float);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment