0

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..

<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>
4
Contributors
4
Replies
7
Views
8 Years
Discussion Span
Last Post by redshadowhack
0

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

1

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("");
	}
Votes + Comments
Very clean code
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.