in reply to Bitwise Complement

Bitwise operators operate on the "internal" bitstrings that represent numbers or strings, not on strings of 1s and 0s. The reason & and | seem to work is that their characters only differ by a bit. When you complement them, you get those weird characters.

Instead of unpacking to B, unpack to L (unsigned long), then do your operations. Then use the %032b format of printf to get the bitstring.

sub is_hostaddress { my $self = shift if ref($_[0]); my $ipaddr = shift; my $netmask = shift; return unless defined($ipaddr) && defined($netmask); my $binipaddr = unpack('L', pack('C4', split(/\./, $ipaddr))); my $binnetmask = unpack('L', pack('C4', split(/\./, $netmask)) +); my $result = $binipaddr & $binnetmask; my $result2 = $binipaddr | ~$binnetmask; # printf "%04x %04x, %04x %04x\n", $binipaddr, $binnetmask, $re +sult, $result2; # printf "%032b\n%032b\n", $binipaddr, $binnetmask; printf "%032b\n%032b\n", $result, $result2; }

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Bitwise Complement
by definitemaybe (Initiate) on Aug 17, 2007 at 21:17 UTC
    Thank you for your help and an example of how to make the code work. Thanks to your help and a few others I'm getting a much better grasp on how I need to be attack the full problem with my code (really my understanding of the workings of Perl).