Php5 package broken on x84_64 env

pack('H*', dechex(12345678900)) /* on 32bit */ != pack('H*', dechex(12345678900)) /* on 64bit */ 

why?

+4
source share
1 answer

I donโ€™t know how to fix it, but I think I know why this is happening. There are no errors here - pull out the manual http://php.net/manual/en/function.dechex.php

The maximum number that can be converted is 4294967295 in decimal format, resulting in "ffffffff"

I don't know what exactly is going on inside "php", but you are probably calling a 32-bit unsigned integer to overflow (12,345,678,900> 4,294,967,295). Since this limit should be 18 446 744 073 709 551 615 for 64 bits, dechex returns the โ€œcorrectโ€ values โ€‹โ€‹(the 32-bit difference of 64 bits does not seem to be documented, and I can be wrong, because I do not have a 64-bit system for testing )

// Change:

As a last resort, you can use GMP extesion to create your own hecdex function for a 32-bit system, but this will produce a lot, a lot of overhead. This will probably be one of the slowest implementations known to modern programming.

// Edit2:

Wrote a function using BCMath , I'm on Windows right now and struggling to find the right dll for GMP.

 function dechex32($i) { //Cast string $i = (string)$i; //Initialize result string $r = NULL; //Map hex values 0-9, af to array keys $hex = array_merge(range(0, 9), range('a', 'f')); //While input is lagrer than 0 while(bccomp($i, '0') > 0) { //Modulo 16 and append hex char to result $r.= $hex[$mod = bcmod($i, '16')]; //i = (i - mod) / 16 $i = bcdiv(bcsub($i, $mod), '16'); } //Reverse result and return return strrev($r); } var_dump(dechex32(12345678900)); /*string(9) "2dfdc1c34"*/ 

Not tested, but seems to work. Using as a last resort - an approximate comparative analysis with 100,000 iterations showed that it is ~ 40 times slower than the native implementation.

+1
source

All Articles