Search code examples
perlbinarydecimal8-bit

Perl Decimal to Binary 32-bit then 8-bit


I've got a number (3232251030) that needs to be translated from Decimal to Binary. Once I've gotten the binary, I need to separate 8-bits of it into digits, revealing an ip address.

Converting Decimal to Binary is simple:

sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; }

sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }

e.g. $num = bin2dec('0110110'); # $num is 54 $binstr = dec2bin(54); # $binstr is 110110

Reference: http://www.perlmonks.org/?node_id=2664

So now, I need to split 8 digits off the binary and save it into numbers that makes an IP address.

$num = dec2bin('3232251030');

($num is "11000000 10101000 01000100 00001110" in binary)

I need to split and save each 8-bits "11000000 10101000 01000100 00001110" into "192.168.60.150".

Care to advice? I'm looking into split function for this..


Solution

  • You don't actually have to convert to a binary string, just a 32-bit integer:

    print join '.', unpack('CCCC', pack('N', 3232251030));
    

    will print 192.168.60.150