简体   繁体   English

在 JS [Javascript] 中将 CIDR 地址从十六进制转换为二进制

[英]Converting CIDR address from Hex to Binary in JS [Javascript]

I'm looking for a way to read a list of CIDR addresses and convert them into a binary strings.我正在寻找一种方法来读取 CIDR 地址列表并将它们转换为二进制字符串。 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.19111000000.10101000.00010100.10111111

192.168.20.16/28 to 11000000.10101000.00010100.00010000 192.168.20.16/2811000000.10101000.00010100.00010000

192.168.0.0/16 to 11000000.10101000.00000000.00000000 192.168.0.0/1611000000.10101000.00000000.00000000

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.它并不完美,因为左侧的零被省略了,但您可以改进此解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM