Bit Pattern in JavaScript

446 Views Asked by At

I would like to ask help whether am I doing the right thing or not. You see I am trying to test myself by displaying the bit pattern of a number in the most efficient way as possible. But I'm having trouble on how to display the pattern cause I'm still learning javascript. Here's my code.

<script>
    var bitPattern = function(given) {
        for(var i = 1 << 31; i > 0; i = i / 2){
            document.write((given & i) ? 1 : 0);
        }
    };

    var number = prompt("Enter a number to convert: ");

    bitPattern(number);
</script>
1

There are 1 best solutions below

3
On BEST ANSWER

The best way to do this is:

var number = prompt("Enter a number to convert: ");
var bitPattern = parseInt(number).toString(2);

document.write(bitPattern);