如何将二进制字符串转换为Perl中的$x_bin="0001001100101"
数值$x_num=613
?
我的首选方式是:
$x_num = oct("0b" . $x_bin);
引用自man perlfunc
:
oct EXPR oct Interprets EXPR as an octal string and returns the corresponding value. (If EXPR happens to start off with "0x", interprets it as a hex string. If EXPR starts off with "0b", it is interpreted as a binary string. Leading whitespace is ignored in all three cases.)
sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
像往常一样,这里还应该提到一个优秀的CPAN模块:Bit :: Vector.
转型看起来像这样:
use Bit::Vector; my $v = Bit::Vector->new_Bin( 32, '0001001100101' ); print "hex: ", $v->to_Hex(), "\n"; print "dec: ", $v->to_Dec(), "\n";
二进制字符串可以是几乎任何长度,你可以做其他整洁的东西,如位移等.
实际上你可以在前面粘上'0b',它被视为二进制数.
perl -le 'print 0b101' 5
但这仅适用于裸字.