Open qappleh opened 3 years ago
function integerToBin (num) { // 64 const result = [] while (num / 2) { next = num % 2 num = Math.floor(num / 2) result.unshift(next) } return result } function fractionalToBin (num) { const result = [] let i = 0 while (num !== 0 && i < 54) { num = num * 2 next = num >= 1 ? 1 : 0 num = num % 1 i++ result.push(next) } return result } function decToBinary (num) { // 1.5 const [int, fraction] = String(num).split(/(?=\.)/).map((x, i) => { return i === 0 ? integerToBin(x) : fractionalToBin(x) }) return [int, fraction] } function binToDec (num) { const [_int, _fraction] = String(num).split('.') const int = _int.split('').reduceRight((acc, x, i) => { return acc + x * 2 ** i }, 0) const fraction = _fraction ? _fraction.split('').reduce((acc, x, i) => { return acc + x * 2 ** -(i + 1) }, 0) : 0 return `${int}${fraction ? '.' + fraction.toString().slice(2) : ''}` } console.log(16, integerToBin(16), Number(16).toString(2)) console.log(18, integerToBin(18), Number(18).toString(2)) console.log(0.5, fractionalToBin(0.5), Number(0.5).toString(2)) console.log(0.1, fractionalToBin(0.1), Number(0.1).toString(2)) console.log(1.1, decToBinary(1.1), Number(1.1).toString(2)) console.log(7.875, decToBinary(7.875), Number(7.875).toString(2)) console.log('111.111', binToDec('111.111'), parseInt('111.111', 2))