#!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub dec2bin { my $bits = shift; my $str = unpack("B8", pack("c", $bits)); return $str; } sub bin2dec { return unpack("c", pack("B8", substr("0" x 8 . shift , -8))); } my @array = (127,-127); foreach $_ (@array){ if ($_ < 0) { print "Value: $_ is negative\n"; my $negative_b = dec2bin($_); print "Negative binary: ".$negative_b."\n"; my $negative_d = bin2dec($negative_b); print "Negative_binary back to decimal: ".$negative_d."\n"; } else { print "Value: $_ is possitive\n"; my $possitive_b = dec2bin($_); print "Possitive binary: ".$possitive_b."\n"; my $possitive_d = bin2dec($possitive_b); print "Possitive_binary back to decimal: ".$possitive_d."\n"; } } __END__ Value: 127 is possitive Possitive binary: 01111111 Possitive_binary back to decimal: 127 Value: -127 is negative Negative binary: 10000001 Negative_binary back to decimal: -127