Decimal to Binary Converter

As usual i searched google to convert Decimal numbers to their Binary equivalents but i couldnt find any short algorithm for that matter. So here is mine..

Deendayal_Hindu commented: var s="213"; function desbin(t){ var num=Number(t); var b=""; while(num>0){ b+=(num%2) var d= num/2; num = Math.floor(d) } return Nu +0
2,491 Views
``````<script type="text/javascript">
function ConvertToBinary(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits.join("");
}
</script>

Example usage :

<input type="text" id="txtDec" />
<input type="button" value="Convert" onclick="document.getElementById('spBin').innerHTML=ConvertToBinary(document.getElementById('txtDec').value);" />
<span id="spBin"></span>``````

Hi,
Thats a handy bit of code. How would I modify it to always show 8 bit binary...ie always display leading zeros ?
Jay

Ooops ... sorry for resurecting a 3 year old post btw :(

Hi, Odessa!

``````function dec2bin(val) {
var bits = [];
for (var i = 0; i < 8; i++) {
bits.push(val % 2);
val = (val - val % 2) / 2;
}
bits.reverse();
return bits.join("");
}``````
mi.mac.rules commented: Very clean code +2

a=1234;
a.toString(2);

var s="213";
function desbin(t) {
var num=Number(t);
var b="";
while(num>0) {
b+=(num%2)
var d= num/2;
num = Math.floor(d)

``     }``

return Number(b); }

console.log(desbin(s));

rproffitt commented: Please be timely. This discussion is 8 years old. -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.