如何用二进制格式表示负数?

问题描述

PHP中,我们可以用二进制格式表示数字。在64位系统上使用正整数,如下所示:

#example storing 262
$a = 262;
$b = 0b0000000000000000000000000000000000000000000000000000000100000110;
$c = 0x0000000000000106;
echo ($a).'<br/>';
echo ($b).'<br/>';
echo ($c).'<br/>';

当到负数时,我不能用二进制和十六进制表示它们,只能用十进制表示。

#**storing -263**
$e = -263; #works fine
$f = 0b1111111111111111111111111111111111111111111111111111111011111001; #wouldn't represent -263
$g = 0xfffffffffffffef9; #wouldn't represent -263
echo ($e).'<br/>';
echo ($f).'<br/>';
echo ($g).'<br/>';

请注意

$b = -263;
echo decbin($b);
#if you run this code you'll see that PHP uses two's complement to store negative numbers and all above binary and hex I provided are correct

为什么我不能使用二进制格式在PHP中表示负数?

我意识到PHP返回的输出是完全错误的。只需使用计算器将上述二进制数转换为十进制,就会看到-268427136不是#int(-268427264)

为什么PHP会这样做?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)