Concept
Let’s take a number 147 for conversion. The calculation will be :
147 = 128 + 16 + 2 + 1
And now we can based on the table above and start allocate 1 for those involved in the calculation and 0 for not involving in the calculation.
Application
function decimalBinaryConverter(decimal){
const decimalArr = [256,128,64,32,16,8,4,2,1]
let binary = ""
for (let bit of decimalArr){
if((decimal & bit) === bit){
binary += "1"
}else{
binary += "0"
}
}
}
// will return `010010011`
console.log(decimalBinaryConverter(147))Explanation
- We first initialize a array variable called
decimalArrwith the decimal values from 2^N - Then we can start to iterate the array and start comparing the argument
decimalwith the index value of ourdecimalArr - We can utilize the bitwise AND operator. More reference on the AND logic gate
(decimal & bit) === bit147 & 128will gives you 128147 & 64will gives you 0147 & 32will gives you 0147 & 16will gives you 16
- And we can based on this condition and convert our decimal to binary number accordingly