架构的一元 NOT/整数大小
来自“掌握 Perl/第 16 章/位运算符/一元 NOT,~”:
一元 NOT 运算符(有时称为补码运算符)~,根据体系结构的整数大小返回值的按位否定或 1 的补码
为什么以下脚本会输出两个不同的值?
#!/usr/local/bin/perl
use warnings;
use 5.012;
use Config;
my $int_size = $Config{intsize} * 8;
my $value = 0b1111_1111;
my $complement = ~ $value;
say length sprintf "%${int_size}b", $value;
say length sprintf "%${int_size}b", $complement;
输出:
32
64
From "Mastering Perl/Chapter 16/Bit Operators/Unary NOT,~":
The unary NOT operator (sometimes called the complement operator), ~, returns the bitwise negation, or 1's complement, of the value, based on integer size of the architecture
Why does the following script output two different values?
#!/usr/local/bin/perl
use warnings;
use 5.012;
use Config;
my $int_size = $Config{intsize} * 8;
my $value = 0b1111_1111;
my $complement = ~ $value;
say length sprintf "%${int_size}b", $value;
say length sprintf "%${int_size}b", $complement;
Output:
32
64
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
intsize 给出了 C 'int' 的宽度,但“体系结构的整数大小”表示 Perl 实际将使用的整数的大小,这可能取决于它的配置方式。使用
$Config{'ivsize'}
(或 uvsize;两者应该相同)来查看它有多长(或使用 ivtype/uvtype 来查看 C 类型是什么)。您看到两个长度之间存在差异,intsize 为 4,但 ivsize 为 8。您使用的格式
%32b
将最小输出宽度设置为 32; $value 仅使用 8 个字符,因此填充为 32 个字符,但 $complement 使用 64 个字符。intsize gives the width of a C 'int', but "the integer size of the architecture" means the size of integer that Perl actually will use, which can depend on how it was configured. Use
$Config{'ivsize'}
(or uvsize; the two ought to be the same) to see how long that is (or ivtype/uvtype to see what the C type is).Where you are seeing a difference between the two lengths, intsize is 4, but ivsize is 8. You are using the format
%32b
which sets a minimum output width of 32; $value only uses 8 characters so is padded out to 32, but $complement uses 64 characters.关键词是“基于架构的整数大小”。您在 64 位架构上运行此程序,因此补码将作为 64 位整数返回。在 32 位架构上运行代码会产生
32 32
的输出。使用
Devel::Peek::Dump
,您可以看到$complement
是一个无符号整数,而$value
不是。 这篇文档表明无符号整数至少为 32 位,但与平台相关。我只能假设它们的意思是“取决于本地 C 编译器调用的‘long’”而不是 int,因为大多数编译器(包括 GCC)在 64 位架构上使用 32 位 int。The key phrase is "based on integer size of the architecture". You're running this on 64 bit architecture, so the complement will be returned as a 64 bit integer. Running the code on 32 bit architecture yields an output of
32 32
.Using
Devel::Peek::Dump
, you can see that$complement
is an unsigned integer whereas$value
is not. This piece of documentation indicates that unsigned integers are at least 32 bits, but platform-dependant. I can only assume they meant "depends on what a local C compiler calls 'long'" rather than int, as most compilers (GCC included) use 32 bit ints on 64 bit architecture.