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

后端 未结 5 1650
别跟我提以往
别跟我提以往 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.

提交回复
热议问题