Skip to content

Instantly share code, notes, and snippets.

@erickzhao
Created March 12, 2018 23:37
Show Gist options
  • Save erickzhao/7e5a25fd9b441edca775b4019dba1ba0 to your computer and use it in GitHub Desktop.
Save erickzhao/7e5a25fd9b441edca775b4019dba1ba0 to your computer and use it in GitHub Desktop.
Convert decimal numbers to Two's Complement binary representation.
const fs = require('fs');
const dec2bin = (dec) => {
return (dec >>> 0).toString(2);
}
fs.readFile('lab2-x.txt', 'utf8', (err,data) => {
// split text into numbers
const a = data.split(' ');
// split numbers into integer portion and fraction portion
const splitNumbers = a.map(a => a.split('.'));
// store max values for W and F
let maxW = 0, maxF = 0;
// iterate through each number
splitNumbers.forEach(number => {
const integer = number[0];
const fraction = number[1];
// get abs value of integer
const abs = Math.abs(integer);
// if greater than max, store integer as max integer
if (abs > maxW) {
maxW = abs;
}
// initialize power as 0
let pow = 0;
// if there's a fraction portion
if (fraction) {
// parse fraction part of string as fraction number
let frac2 = parseInt(fraction)/Math.pow(10, fraction.length);
// run binary fraction converter
while(frac2 > 0) {
pow--; // decrement power every time
// subtract lower powers of 2 (if possible) until we reach 0.
const subtractor = Math.pow(2,pow);
if (frac2 >= subtractor) {
frac2 -= subtractor;
}
}
}
// if power is lower than before, store as largest # of powers of 2 needed
if (pow < maxF) {
maxF = pow;
}
});
// get number of digits for maxW (get log, add 1 for sign)
// get number of digits for maxF
console.log(Math.ceil(Math.log2(maxW))+1, Math.abs(maxF));
const W = Math.ceil(Math.log2(maxW))+1;
const F = Math.abs(maxF);
// get binary
const bin = a.map(num => {
const isNegative = num < 0;
let int = (Math.round(num*Math.pow(2, F)));
if (!isNegative) {
return "0".repeat(10-dec2bin(int).length) + dec2bin(int);
} else {
return dec2bin(int).substr(31-9,10);
}
});
for (let i = 0; i < 5; i++) {
console.log(a[i], bin[i]);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment