Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re^2: Bitwise AND with large numbers

by mdej (Initiate)
on Apr 16, 2012 at 16:56 UTC ( #965357=note: print w/replies, xml ) Need Help??

in reply to Re: Bitwise AND with large numbers
in thread Bitwise AND with large numbers


Thank you for your quick reactions ;-)
Using Math::BigInt or pack I unfortunately still get an integer overflow. I'm probably doing something wrong but don't see what. Sorry if this is to much of a newbie question.

A little more context: The hexstring comes from a switch. I want to use the hexstring to determine if a switchport is member of a specific VLAN. The code I have so far is:
my $switchPortNumber = 2; # 32 Character hex string from switch my $hexstring = hex '40000000000000000000000000000000'; my $mask = (0x80000000000000000000000000000000 >> $switchPortNumber); my $result = ($hexstring & $mask) > 0;
In this case only the first port is a member and the second port is NOT a member. Therefore the $result should be 0

If possible I would like to stick to the default Perl modules.
Thanks again for all the help so far.

Replies are listed 'Best First'.
Re^3: Bitwise AND with large numbers
by Eliya (Vicar) on Apr 16, 2012 at 17:12 UTC

    This works fine for me:

    use Math::BigInt; my $switchPortNumber = 2; # 32 Character hex string from switch my $hexstring = Math::BigInt->new('0x40000000000000000000000000000000' +); my $mask = (Math::BigInt->new('0x80000000000000000000000000000000') >> + $switchPortNumber); my $result = ($hexstring & $mask) > 0;

    Another approach would be to turn it into an ASCII bitstring, in which case you can use a simple substr() instead of the AND masking

    my $bitstring = unpack('B*', pack('H*', '40000000000000000000000000000 +000')); my $result = substr($bitstring, $switchPortNumber, 1) eq '1';
      Hey Eliya,

      Thanks for the quick response. Your solutions look promising. I especially like the one where you turn the hex string in a ASCII bit string. I will try this with my code and test it with the switch. I will let you know how things went.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://965357]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2018-03-24 20:31 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (299 votes). Check out past polls.