The following code takes a decimal number and gives its IEEE 754 floating point representation. However, the code is not complete and I am totally fine because it does the job for me:
- It does not consider negative numbers.
- The input number is not a fraction. Its always in the form xx.yy
- As of now, it does not give representation in 32-bit or 64-bit format, it just gives exponent and significant value.
function toBinary (decimal) {
return decimal.toString(2);
}
function getIntegerPart (binary){
return binary.slice(0, binary.indexOf('.'));
}
function getFractionalPart (binary){
return binary.slice(binary.indexOf('.')+1);
}
function toNormalize (binary) {
var normalizedRep = new Object();
exponentValue = binary.indexOf('.')-1;
floatPosition = binary.indexOf('.');
normalizedRep.floatRep = binary[0]+ '.' + binary.slice(1, floatPosition) + binary.slice(floatPosition+1);
normalizedRep.exponentValue = exponentValue;
normalizedRep.floatPosition = floatPosition;
return normalizedRep;
}
function getSignificand (normalizedRep) {
return normalizedRep.floatRep.slice(normalizedRep.floatRep.indexOf('.')+1);
}
function twosComp() {
var decimal = 15.22;
var binary = toBinary(decimal);
var integerPart = getIntegerPart(binary);
var fractionalPart = getFractionalPart(binary);
var floatPosition = binary.indexOf('.');
var normalizedRep = toNormalize(binary);
var significand = getSignificand(normalizedRep);
var exponentValue = normalizedRep.exponentValue;
console.log(binary);
console.log(floatPosition);
console.log(normalizedRep.floatRep);
console.log(significand);
console.log(exponentValue);
}