ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
2.4. Converting Between Binary and DecimalProblemYou have an integer whose binary representation you'd like to print out, or a binary representation that you'd like to convert into an integer. You might want to do this if you were displaying non-textual data, such as what you get from interacting with certain system programs and functions. SolutionTo convert a Perl integer to a text string of ones and zeros, first pack the integer into a number in network byte order[1] (the "
sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; } To convert a text string of ones and zeros to a Perl integer, first massage the string by padding it with the right number of zeros, then just reverse the previous procedure. sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } DiscussionWe're talking about converting between strings like " The We use We use $num = bin2dec('0110110'); # $num is 54 $binstr = dec2bin(54); # $binstr is 110110 See AlsoThe |