如何有效地使用 Perl 中的 BitVector 模块来查找两个数字的 XOR?

How to effectively use the BitVector Module In Perl to find the XOR of two numbers?

我无法弄清楚如何有效地使用 Perl 中的 BitVector 模块来查找十六进制形式的两个数字的异或 (XOR)。

这是我的全部代码:

use Bit::Vector;
$bits = Bit::Vector->Word_Bits();  #  bits in a machine word

print "This program will take two numbers and will return the XOR of the two numbers.\n";

print "Enter the first number in hexadecimal form:\n";
$firstHexNumber = <STDIN>;
$vector = Bit::Vector->new($bits, $firstHexNumber);  #  bit vector constructor

print "Enter the second number in hexadecimal form:\n";
$secondHexNumber = <STDIN>;
$vector2 = Bit::Vector->new($bits, $secondHexNumber);  #  bit vector constructor

$vector3 = Bit::Vector->new($bits);  #  bit vector constructor
$vector3->Xor($vector,$vector2);

print $vector3;

我不确定我的语法是否适合 BitVector 模块。 如果我尝试 运行 它,我会得到这样的输出。 Output

当我输入 1 和 16 作为参数时,输出应该是 17。 请帮我看看我的代码有什么问题以使输出正确。 谢谢。

您可以使用 new_Hex() and to_Hex():

use strict;
use warnings;
use Bit::Vector;
my $bits = Bit::Vector->Word_Bits();  #  bits in a machine word
my $firstHexNumber = "1";
my $vector = Bit::Vector->new_Hex($bits, $firstHexNumber); 
my $secondHexNumber = "17";
my $vector2 = Bit::Vector->new_Hex($bits, $secondHexNumber);
my $vector3 = Bit::Vector->new($bits);  #  bit vector constructor
$vector3->Xor($vector,$vector2);
print $vector3->to_Hex;

输出:

0000000000000016

不需要模块。

# Make sure the bitwise feature wasn't activated (e.g. by `use 5.022;`)
no if $] >= 5.022, feature => qw( bitwise );

my $hex1 = '012345';
my $hex2 = '000AAA';

my $hex_xor = unpack('H*', pack('H*', $hex1) ^ pack('H*', $hex2) );

say $hex_xor;  # 0129ef

或 (5.22+)

# Safe. Feature accepted without change in 5.28.
use experimental qw( bitwise );

my $hex1 = '012345';
my $hex2 = '000AAA';

my $hex_xor = unpack('H*', pack('H*', $hex1) ^. pack('H*', $hex2) );

say $hex_xor;  # 0129ef

或 (5.28+)

use feature qw( bitwise );  # Or: use 5.028;  # Or: use v5.28;

my $hex1 = '012345';
my $hex2 = '000AAA';

my $hex_xor = unpack('H*', pack('H*', $hex1) ^. pack('H*', $hex2) );

say $hex_xor;  # 0129ef

这些解决方案适用于任意长度的数字,这就是我假设选择使用 Bit::Vector 的原因。 (如有必要,只需填充数字,使两者具有相同的长度,否则 Perl 将有效地向右填充零。)