How do I convert a binary string to a number in Perl?

后端 未结 5 1620
别跟我提以往
别跟我提以往 2020-12-13 00:44

How can I convert the binary string $x_bin=\"0001001100101\" to its numeric value $x_num=613 in Perl?

相关标签:
5条回答
  • 2020-12-13 00:51

    As usual, there's is also an excellent CPAN module that should be mentioned here: Bit::Vector.

    The transformation would look something like this:

    use Bit::Vector;
    
    my $v = Bit::Vector->new_Bin( 32, '0001001100101' );
    print "hex: ", $v->to_Hex(), "\n";
    print "dec: ", $v->to_Dec(), "\n";
    

    The binary strings can be of almost any length and you can do other neat stuff like bit-shifting, etc.

    0 讨论(0)
  • 2020-12-13 00:51

    Actually you can just stick '0b' on the front and it's treated as a binary number.

    perl -le 'print 0b101'
    5
    

    But this only works for a bareword.

    0 讨论(0)
  • 2020-12-13 01:05

    You can use the eval() method to work around the bare-word restriction:

    eval "\$num=0b$str;";
    
    0 讨论(0)
  • 2020-12-13 01:10
    sub bin2dec {
        return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
    }
    
    0 讨论(0)
  • 2020-12-13 01:15

    My preferred way is:

    $x_num = oct("0b" . $x_bin);
    

    Quoting from 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.)
    
    0 讨论(0)
提交回复
热议问题