如何将二进制字符串转换为Perl中的数字?

Nat*_*man 29 binary perl

如何将二进制字符串转换为Perl中的$x_bin="0001001100101"数值$x_num=613

Nat*_*man 58

我的首选方式是:

$x_num = oct("0b" . $x_bin);
Run Code Online (Sandbox Code Playgroud)

引用自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.)

  • 我总是使用pack,但我只是对pack,oct和Bit :: Vector进行了基准测试,这是迄今为止三者中最快的.它比Bit :: Vector快1449%,比我的系统打包快316%. (2认同)

Ed *_*ess 24

sub bin2dec {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}
Run Code Online (Sandbox Code Playgroud)

  • 我询问的每个工具都告诉我,111111111111111111111111111111111翻译为8589934591.您对42949672958589934591是否正确无疑? (3认同)
  • 这也是由内置的oct()完成的,虽然它的名字很差. (2认同)

inn*_*naM 12

像往常一样,这里还应该提到一个优秀的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";
Run Code Online (Sandbox Code Playgroud)

二进制字符串可以是几乎任何长度,你可以做其他整洁的东西,如位移等.


nos*_*nky 6

实际上你可以在前面粘上'0b',它被视为二进制数.

perl -le 'print 0b101'
5
Run Code Online (Sandbox Code Playgroud)

但这仅适用于裸字.