需要解释“~0”与“2**64”(带和不带“使用整数”)

2024-02-18

我编写了一些测试程序打印的值~0 and 2**64:

#!/usr/bin/perl
use warnings;
use strict;
#use integer;
print ~0, "\n";
print 2**64, "\n";

Without use integer程序输出

118446744073709551615
1.184467440737096e+19

With use integer程序输出:

-1
1.184467440737096e+19

另一个奇怪的事情是,即使使用print int(2**64)该数字仍然以科学格式输出,就像int(...)不在那里(仍然~0没有use integer以“整数格式”输出)。

我可以使用强制整数输出printf("%u\n", ...), 然而。

(Perl 在 x86_64 上的 SLES12 SP5 5.18.2 中使用)

问题:

那么为什么是2**64有和没有的“浮动”use integer, while ~0从来没有?

use integer when ~0打印为-1,仍然满足条件~0 > 2**63(当我期望-1 not大于任何正值(例如2**63).

Update

Perl 调试器中似乎还出现了另一个奇怪的效果:2^64是奇数,并且2^64-1 is -2.

  DB<22> if (1) { use integer; print 2**64, "\n" }
1.84467440737096e+19

  DB<23> if (1) { use integer; print 2**64 - 1, "\n" }
-2
  DB<13> if (1) { use integer; printf '%x', 2**64-1, "\n" }
fffffffffffffffe
  DB<14> if (1) { use integer; printf '%x', 2**64, "\n" }
ffffffffffffffff
  DB<15> if (1) { no integer; printf '%x', 2**64, "\n" }
ffffffffffffffff
  DB<16> if (1) { no integer; printf '%x', 2**63, "\n" }
8000000000000000

那么为什么是2**64有和没有的“浮动”use integer

求幂是使用浮点数计算的,从而产生浮点数。我不知道为什么use integer不会强制将结果转换为有符号整数,但事实并非如此。这与其文档一致,文档指出该编译指示仅影响以下操作数和结果:

  • 算术运算符 (+, -, *, /, %, +=, -=, *=, /=, %=,和一元减号)
  • 比较运算符 (<, <=, >, >=, ==, !=, <=>), and
  • 按位运算符 (|, &, ^, <<, >>, |=, &=, ^=, <<=, >>=)

事实上,它专门排除了**.

电力运营商**也不受影响,因此 2 ** .5 始终是 2 的平方根。


while ~0从来没有?

机器只有对整数类型执行按位运算的操作,并且它们返回整数类型。将数字转换为浮点数是没有意义的(并且有很多理由不使用 64 位整数进行构建)。

use integer when ~0打印为-1,仍然满足条件~0 > 2**63(当我期望-1 not大于任何正值(例如2**63).

use integer导致许多运算符将值转换为 IV,并且<就是这样一个运营商。铸件2**63在我的机器上产生 -9223372036854775808 。

$ perl -M5.010 -Minteger -e'say 0 + 2**63'
-9223372036854775808
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

需要解释“~0”与“2**64”(带和不带“使用整数”) 的相关文章

随机推荐