php中二进制的负64位十进制数 [英] Negative 64bit Decimal Number to Binary in php

查看:136
本文介绍了php中二进制的负64位十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换一个十进制数字

I am trying to convert a decimal number for example

-268427136

-268427136

转换为二进制,反之亦然.

to binary and vice versa.

如果我尝试使用Windows Calc,则此数字的二进制表示法是:

If I try with windows Calc, binary notation for this number is:

1111111111111111111111111111111111110000000000000010000010000000

1111111111111111111111111111111111110000000000000010000010000000

如果我尝试bindec,decbin或base_convert: echo(decbin(-268427136));输出:

If I try bindec,decbin or base_convert: echo(decbin(-268427136)); Outputs:

11110000000000000010000010000000

11110000000000000010000010000000

echo(bindec('1111111111111111111111111111111111110000000000000010000010000000');输出:

1.84467440734E + 19

1.84467440734E+19

我可以在php中使用什么来达到相同的结果?

What could I use in php to achieve same result?

推荐答案

您的PHP可能是为32位系统编译的,导致整数溢出和数字以32位表示.确保您的PHP是为64位编译的.

Your PHP is probably compiled for 32bit systems resulting in integer overflow and number being represented in 32bit. Ensure that your PHP is compiled for 64bit.

您可以使用

<?php
echo PHP_INT_SIZE;

这应该返回8.在我的PHP上,以下工作方式为PHP_INT_SIZE为8:

this should return 8. On my PHP the following works as PHP_INT_SIZE is 8:

php > echo(decbin(-268427136));
1111111111111111111111111111111111110000000000000010000010000000

背景

PHP使用C语言类型long在内部表示整数(PHP用C编写).这些是平台相关的.在64位系统上,这些通常为64位长.在Windows上,尽管系统支持64位,但有时将诸如PHP之类的应用程序编译为32位,导致long32bit4byte.因此,您将得到一个溢出,导致一个32位长的数字.您的情况:11110000000000000010000010000000

Background

PHP uses the C language type long to represent integers internally (PHP is written in C). These are platform dependent. On 64bit system usually these are 64bit long. On Windows sometimes applications such as PHP are compiled for 32bit, despite the system supporting 64bit, resulting in long being 32bit or 4byte. Thus you get an overflow which results in a 32bit long number. In your case: 11110000000000000010000010000000

根据PHP手册, bindec 返回一个数字.由于您的数字是64位,因此PHP会将其解释为浮点数.它使用不带符号的整数或浮点数计算截止值.参见 2 .

According to the PHP manual, bindec returns a number. As your number is 64bit, PHP interprets it as a float. It calculates the cutoff for using integer or float without the sign. See 2.

php > var_dump(bindec('1111111111111111111111111111111111110000000000000010000010000000'));
float(1.8446744073441E+19)

可以通过显式强制转换为int来防止这种情况.

This can be prevented by explicitly casting to int.

php > var_dump((int)bindec('1111111111111111111111111111111111110000000000000010000010000000'));
int(-268427264)

这篇关于php中二进制的负64位十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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