0

I'm looking for a way to read a list of CIDR addresses and convert them into a binary strings. The input is a file with rows of actions and addresses and destinations:

ADD 192.168.20.16/28 A

FIND 255.255.255.0

REMOVE 192.168.20.16/28 A

How can I convert these addresses to binary? For example:

192.168.20.191 to 11000000.10101000.00010100.10111111

192.168.20.16/28 to 11000000.10101000.00010100.00010000

192.168.0.0/16 to 11000000.10101000.00000000.00000000

ksilla
  • 101
  • 10

1 Answers1

0

From here.


function dec2bin(dec){
    return dec.toString(2);
}

const ips = ["192.168.20.191", "192.168.20.16", "192.168.0.0"]

ips.forEach((ip, index) => {
  const parts = ip.split(".")
  
  const newParts = []
  parts.forEach(part => {
    newParts.push(dec2bin(parseInt(part)))
  })
  
  ips[index] = newParts.join(".")
})

console.log(ips)

It's not perfect, because of zeros to the left, which are omitted, but you can improve this solution.

Grampet
  • 177
  • 1
  • 1
  • 8
  • Yeah I've seen this solution, but I don't get how to convert CIDR notation to binary correctly. >For example:192.168.20.16/28 – ksilla Jul 27 '20 at 12:10