perlxorbitvector

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


I am having trouble figuring out how to effectively use the BitVector module in Perl to find the Exclusive Or (XOR) of two numbers in hexadecimal form.

This is my whole code:

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;

I am not sure if I am doing the syntax right for the BitVector module. If I try to run it, I get an output like this. Output

When I input 1 and 16 as my arguments, the output is supposed to be 17. Please help me see what's wrong with my code to get the output correct. Thank you.


Solution

  • You can use 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;
    

    Output:

    0000000000000016