混淆PHP按位NOT行为 [英] Confusing PHP bitwise NOT behavior

查看:51
本文介绍了混淆PHP按位NOT行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,如果我运行以下简单程序

In PHP, if I run the following simple program

$number = 9;
var_dump( ~ $number );

我的输出是

int(-10)

这让我感到困惑.我认为 ~是按位的NOT运算符.所以我期待着类似的事情.

This is confusing to me. I thought ~ was the bitwise NOT operator. So I was expecting something like.

if binary 9 is     00000000000000000000000000001001 
then Bitwise NOT 9 11111111111111111111111111110110

含义~9应该以类似于4,294,967,286的一些荒谬的大整数形式出现.

Meaning ~9 should come out as some ludicrously large integer like 4,294,967,286.

什么是优先级,强制类型,或者我在这里还缺少其他什么?

What subtly of precedence, type coercion, or something else am I missing here?

推荐答案

您的输出默认为带符号的int-将其包装在decbin中以获取二进制表示形式.

Your output is defaulting to a signed int - wrap it in decbin to get a binary representation.

考虑:

$number = 9;
var_dump(  bindec(decbin(~ $number)) );

使用双重赞美,即

With two's compliment, the MSB of a signed binary number becomes 0-MSB, but every other bit retains its respective positive values.

因此,为了论证(一个8位示例),

So for argument's sake (an 8-bit example),

Binary 9: 0000 1001
Inverse:  1111 0110

结果为(-128) + 64 + 32 + 16 + 4 + 2 = -10,因此PHP可以正确计算,只需对MSB应用2的补码即可.

This results in (-128) + 64 + 32 + 16 + 4 + 2 = -10, so PHP is calculating correctly, its just applying two's compliment to the MSB.

这篇关于混淆PHP按位NOT行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆