gpt4 book ai didi

perl - perl。将64位二进制数转换为十进制

转载 作者:行者123 更新时间:2023-12-04 22:52:49 26 4
gpt4 key购买 nike

我有一个包含64个二进制符号的字符串。

我需要将其转换为十进制数。如何在Perl中做到这一点?

sub bin2dec {
return unpack("N", pack("B64", substr("0" x 64 . shift, -64)));
}


不起作用。它只转换前32位。

最佳答案

docs中,

N  An unsigned long (32-bit) in "network" (big-endian) order.


64位等效项为“ Q>”。

q  A signed quad (64-bit) value.
Q An unsigned quad value.
(Quads are available only if your system supports 64-bit
integer values _and_ if Perl has been compiled to support
those. Raises an exception otherwise.)

> sSiIlLqQ Force big-endian byte-order on the type.
jJfFdDpP (The "big end" touches the construct.)


因此,您可以使用以下代码:

unpack("Q>", pack("B64", substr("0" x 64 . shift, -64)))




就是说,以上内容不必要地复杂。编码的人可能都不了解 oct解析二进制数字的能力,因为上述内容可以简化为

oct("0b" . shift)




但是,如果没有64位的Perl,该怎么办?您需要使用某种使数学运算过载的对象。您可以使用 Math::BigInt,但是我怀疑它的速度不如 Math::Int64

use Math::Int64 qw( string_to_int64 );
string_to_int64(shift, 2)


例如,

$ perl -MMath::Int64=string_to_int64 -E'say string_to_int64(shift, 2);' \
100000000000000000000000000000000
4294967296

关于perl - perl。将64位二进制数转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10555770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com