#!/usr/bin/perl use strict; use warnings; my @array = (3,-3); foreach $_ (@array){ if ($_ < 0) { print "Value: $_ is negative\n"; my $negative_b = dec2bin($_,32,"i"); print "Negative binary: ".$negative_b."\n"; my $negative_d = bin2dec($negative_b,"i"); print "Negative_binary back to decimal: ".$negative_d."\n"; } else { print "Value: $_ is possitive\n"; my $possitive_b = dec2bin($_,8,"N"); print "Possitive binary: ".$possitive_b."\n"; my $possitive_d = bin2dec($possitive_b,"N"); print "Possitive_binary back to decimal: ".$possitive_d."\n"; } } sub dec2bin { my $bits = shift; my $possition = shift; my $template = shift; my $str = unpack("B32", pack($template, $bits)); $str = substr $str, -$possition; return $str; } sub bin2dec { my $bits = shift; my $template = shift; return unpack($template, pack("B32", substr("0" x 32 . $bits , -32))); } __END__ Value: 3 is possitive Possitive binary: 00000011 Possitive_binary back to decimal: 3 Value: -3 is negative Negative binary: 11111101111111111111111111111111 Negative_binary back to decimal: -3