1

Take this IP address:

192.168.1.1

I want to break it down into 4 full binary octets, so:

11000000 . 10101000 . 00000001 . 00000001.


All of the conversions I know, and those that I've found on other stackoverflow questions, only return the binary number itself, for example:

(1 >>> 0).toString(2) returns 1 when I want 00000001

Number(2).toString(2) returns 10 when I want 00000010


Is there an in-built javascript method that I haven't come across yet or do I need to manually add the 0's before depending on the number?

Apswak
  • 3,632
  • 4
  • 24
  • 52

2 Answers2

2

You can use Number#toString method with radix 2 for converting a Number to corresponding binary String.

var str = '192.168.1.1';

console.log(
  // Split strings based on delimiter .
  str.split('.')
  // iterate over them 
  .map(function(v) {
    // parse the String and convert the number to corresponding 
    // binary string afterwards add preceding 0's 
    // with help of slice method
    return ('00000000' + Number(v).toString(2)).slice(-8)
      // rejoin the string
  }).join('.')
)
Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157
1

The simplest solution is to prefix the answer with zeros and then use a negative substring value to count from the right, not the left...

alert(("00000000" + (1 >>> 0).toString(2)).substr(-8));
Reinstate Monica Cellio
  • 24,939
  • 6
  • 47
  • 65