use strict; use warnings; my $value = 51; # Accumulate binary digits ("bits") my @bits = ( ); foreach my $place (0 .. 7) { my $nextbit = mask_off_bit($value, $place); push @bits, $nextbit; } # Display each bit printf "\nNumber %3d in binary is: ", $value; map { print "$_" } reverse @bits; print "\n"; # Test the results against good ol' printf printf " Which is the same as: %08b\n", $value; sub mask_off_bit { my ($num, $place) = @_; my $mask = 1 << $place; # Same as 2 ** $place my $mstr = " " x (8 - $place) . "^"; # Graphic representation printf " Num %3d: 0b%08b\n", $num, $num; # Number in decimal & binary my $bit = ($mask == ($num & $mask))? 1: 0; # Next bit is one or zero printf "Mask %3d: %s => bit %d\n", $mask, $mstr, $bit; return $bit; } #### my $bit = ($mask == ($num & $mask))? 1: 0