Perl 十进制转二进制 32 位然后 8 位
我有一个数字(3232251030)需要从十进制转换为二进制。 获得二进制文件后,我需要将其 8 位分成数字,从而显示 IP 地址。
将十进制转换为二进制很简单:
sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; }
sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
e.g. $num = bin2dec('0110110'); # $num is 54 $binstr = dec2bin(54); # $binstr is 110110
参考:http://www.perlmonks.org/?node_id=2664< /a>
所以现在,我需要从二进制中分离出 8 位数字并将其保存为构成 IP 地址的数字。
$num = dec2bin('3232251030');
($num 是二进制的“11000000 10101000 01000100 00001110”)
我需要将每个8位“11000000 10101000 01000100 00001110”拆分并保存为“192.168.60.150”。
需要建议吗?我正在研究 split 函数。
I've got a number (3232251030) that needs to be translated from Decimal to Binary.
Once I've gotten the binary, I need to separate 8-bits of it into digits, revealing an ip address.
Converting Decimal to Binary is simple:
sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; }
sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
e.g. $num = bin2dec('0110110'); # $num is 54 $binstr = dec2bin(54); # $binstr is 110110
Reference: http://www.perlmonks.org/?node_id=2664
So now, I need to split 8 digits off the binary and save it into numbers that makes an IP address.
$num = dec2bin('3232251030');
($num is "11000000 10101000 01000100 00001110" in binary)
I need to split and save each 8-bits "11000000 10101000 01000100 00001110" into "192.168.60.150".
Care to advice? I'm looking into split function for this..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您实际上不必转换为二进制字符串,只需转换为 32 位整数即可:
将打印
192.168.60.150
You don't actually have to convert to a binary string, just a 32-bit integer:
will print
192.168.60.150
和
两个输出
and
both output