binary number n vice versa nodejs
4 years ago in JavaScript
app.get('/binary-to-number/:binary', (req,res) => {
var binary = req.params.binary
var power = binary.length-1
var count = 0
for (var i = 0; i < binary.length; i++) {
number = parseInt(binary.charAt(i),10)
number = number * Math.pow(2,power)
count = number + count
power = power - 1
}
res.json({"decimal" : count})
// var int = parseInt(binary,2)
// console.log(int)
// if (!isNaN(int)){ // check if variabel int is a number
// res.json({"decimal" : int})
// }
// else //if variable int is not a number
// res.status(400).json({"message" : "not a binary"})
})
app.get('/number-to-binary/:number', (req,res) => {
var number = req.params.number
var quotient = number
var remainder = number
// quotient = hasil bagi
// remainder = hasil mod
var binaryString = ""
while(quotient != 0){
remainder = quotient % 2
quotient = Math.floor(quotient/2)
bit = remainder
binaryString = bit + binaryString
}
res.json({"binary" : binaryString})
// var parseNumber = parseInt(number,10)
// if(!isNaN(parseNumber)){
// var binary = parseNumber.toString(2)
// res.json({"binary" : binary})
// }
// else{
// res.status(400).json({"message" : "Not a Number"})
// }
})