JSFiddle - React, Tailwind, and code Playground
by darul75
HTML
<input type="text" value="2.25" id="number">
JavaScript
var BITS_MANT_SIMPLE = 23;
var BITS_MANT_DOUBLE = 52;
var BITS_EXP_SIMPLE = 8;
var BITS_EXP_DOUBLE = 11;
var expBase2 = exp();
// method
function IEEE754Encoding(number, double) {
var pm = double ? BITS_MANT_DOUBLE: BITS_MANT_SIMPLE;
var pe = double ? BITS_EXP_DOUBLE : BITS_EXP_SIMPLE;
// - convert and normalize the integer part into binary
// - by splitting number into integer/fraction
// - and computing binary representation
// integer
var int = floor(number);
var bInt = numToBinaryStr(int);
console.log('binary int ' + bInt);
// fraction (decimal)
var fraction = number - int,
bDec = '',
i = 0,
space = pm - bInt.length; // mantissa free space
while (i++ < space) {
var value = fraction * 2;
if (value === 0) break;
var int = floor(value);
bDec += '' + int;
fraction = value - int;
}
// normalise decimal position to get exponent
var isZero = false;
var idx = -1;
var exposant = bInt.length - 1;
if (exposant == 0) {
idx = bDec.indexOf('1') + 1;
exposant = -idx;
isZero = true;
}
// (51,375)10 = (1, 10011011000)base2x2^5
console.log('('+number+') base 10 = ('+bInt+','+bDec+')base 2 * 2^' +exposant);
// remove first useless bit
bDec = !isZero ? bDec : bDec.substring(idx);
var mantis = bInt.substring(1, bInt.length) + bDec;
console.log(mantis);
if (mantis.length < pm) {
mantis = fillBits(mantis, pm - mantis.length, true);
}
check(exposant, mantis);
// binary exposant
exposant += double ? 1023 : 127;
console.log('final exposant ' + exposant);
exposant = numToBinaryStr(exposant);
console.log('binary exposant ' + exposant);
if (exposant.length...