Concept
Based on the table above, we can then utilize the decimal value for the decimal to binary number subtraction.
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.
Final result: 010010011
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
decimalArr
with the decimal values from 2^N - Then we can start to iterate the array and start comparing the argument
decimal
with the index value of ourdecimalArr
- We can utilize the bitwise AND operator. More reference on the AND logic gate
(decimal & bit) === bit
147 & 128
will gives you 128147 & 64
will gives you 0147 & 32
will gives you 0147 & 16
will gives you 16
- And we can based on this condition and convert our decimal to binary number accordingly