Decimal to Binary Converter

serkan sendur 1 Tallied Votes 3K Views Share

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
<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>
odessa 0 Newbie Poster

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

odessa 0 Newbie Poster

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

dimkaben 2 Newbie Poster

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
redshadowhack 0 Newbie Poster

a=1234;
a.toString(2);

Deendayal_Hindu -3 Newbie Poster

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.