-2

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>
6
  • what output are you seeing? Commented Jun 22, 2015 at 14:52
  • for (var i = 31; i >= 0; i--) { bit = (given >> i) & 1 } would probably be a lot more efficient. Commented Jun 22, 2015 at 14:53
  • Seriously, wat? Just num.toString(2)? Commented Jun 22, 2015 at 14:53
  • Alternatives to document.write Commented Jun 22, 2015 at 14:55
  • Whatever about the most efficient way, this won't work because << returns a negative number. You can use (1 << 31) >>> 0, see stackoverflow.com/a/1908655/1469259 Commented Jun 22, 2015 at 14:56

1 Answer 1

3

The best way to do this is:

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

document.write(bitPattern);
Sign up to request clarification or add additional context in comments.

3 Comments

I tried using this but it would display the original number rather than the bit pattern
What about now? But I prefer console output over writing results into web page.
The previous one actually worked. Just forgot to add a "+" to my variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.