for ($foo=1; $foo<211;$foo++){ print "$foo ". dec2bin($foo) . " binrounded is "; $binfoo= (binround ($foo)); print "$binfoo\n"; } sub binround{ my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; $str=~/^.(.*)/; #first char should always be 1, thanks to above. $str="1" . "0" x (length ($1)+(($1=~/1/))); } sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; }