user1668133 user1668133 - 2 months ago 12
PHP Question

Negative 64bit Decimal Number to Binary in php

I am trying to convert a decimal number for example


-268427136


to binary and vice versa.

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


1111111111111111111111111111111111110000000000000010000010000000


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


11110000000000000010000010000000


Or
echo(bindec('1111111111111111111111111111111111110000000000000010000010000000');
Outputs:


1.84467440734E+19


What could I use in php to achieve same result?

Answer

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.

You can check that with

<?php
echo PHP_INT_SIZE;

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

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

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

bindec and 64bit numbers

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)

This can be prevented by explicitly casting to int.

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