gpt4 book ai didi

Perl 按位 AND 给我奇怪的结果

转载 作者:行者123 更新时间:2023-12-03 03:28:08 24 4
gpt4 key购买 nike

我正在编写一个小 Perl 脚本来使用 Perls 按位 AND 运算符来比较两个 IP 地址。但我得到了一些非常有趣的结果。我是 Perl 新手,所以也许有人可以给我一些指示。

这是我的小脚本:

#!/usr/bin/perl

$address = "172.34.12.0";
$address2 = "255.255.255.0";

@octets = split (/\./,$address);
@octets2 = split (/\./,$address2);

#Funky results when doing a bitwise AND
#This outputs "050 24 00 0" What's going on here?
print $octets[0] & $octets2[0], "\n";
print $octets[1] & $octets2[1], "\n";
print $octets[2] & $octets2[2], "\n";
print $octets[3] & $octets2[3], "\n";

#Results are what I want when doing it as literals
#This outputs "172 34 12 0"
print 172 & 255, "\n";
print 34 & 255, "\n";
print 12 & 255, "\n";
print 0 & 0, "\n";

有人知道我在 $octets 和 $octets2 成员上执行按位 AND 时为什么或如何得到“050 24 00 0”吗?当我使用文字进行按位与操作时,一切似乎都工作得很好。请帮忙。谢谢!

最佳答案

按位运算对字符串和数字的作用不同,split 返回字符串。使用 0+int 将字符串转换为数字。 http://codepad.org/sqHntIgZ :

#!/usr/bin/perl

$address = "172.34.12.0";
$address2 = "255.255.255.0";

@octets = split (/\./,$address);
@octets2 = split (/\./,$address2);

#Funky results when doing a bitwise AND
#This outputs "050 24 00 0" What's going on here?
print int($octets[0]) & int($octets2[0]), "\n";
print int($octets[1]) & int($octets2[1]), "\n";
print int($octets[2]) & int($octets2[2]), "\n";
print int($octets[3]) & int($octets2[3]), "\n";

#Results are what I want when doing it as literals
#This outputs "172 34 12 0"
print 172 & 255, "\n";
print 34 & 255, "\n";
print 12 & 255, "\n";
print 0 & 0, "\n";

关于Perl 按位 AND 给我奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7478431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com