Search This Blog

Wednesday, January 4, 2012

Decimal to Hex of a 64bit int on a 32bit PHP System

A small issue raised its head today and required some furious action.

Given a 32bit PHP binary not capable of running dechex() on a 64 bit decimal, how would you convert said 'string' to a hex 'string'.

Enter the cool little code snippet below.

The only requirements for this to function is core php + BCMath.

$id = '1388944919774473767';
$fred = '';
while (bcdiv($id,'16','0') != 0) {
$base = bcdiv($id,'16','0');
$re = bcmod($id,'16');
$fred .= dechex($re);
$id = $base;
$fred .= dechex($id);
echo strrev($fred);

This produced the required result over many many tests. The basis of this base conversion was pulled from here


1 comment:

SLeo said...

You can not use strrev on hexidemical string, only on binary string. This can lead to data corruption.