Press "Enter" to skip to content

Tag: 32bit

PHP: md5 hashes, base_convert and 32 bit limitations

I’ve had cause to convert an md5 hash from the standard hexadecimal base 16 to base 36 (mainly to make it shorter for presentation purposes). However, using base_convert in PHP proved unreliable as the string wouldn’t always convert back correctly. This is on 64 bit Linux, but I’m not certain PHP has been compiled with 64 bit support (so it is probably defaulting to 32bit).

However, thanks to this post on the PHP documentation, I’ve changed the code to use:

/*use gmp library to convert base. gmp will convert numbers > 32bit*/
if (!function_exists('gmp_strval')) {
    trigger_error('GMP does not appear to be compiled into PHP');
}
function gmp_convert($num, $base_a, $base_b)
{
        return gmp_strval ( gmp_init($num, $base_a), $base_b );
}

To test this, here’s the code I used:
function testconvert() {
    $a=Array(10,23,46,239423, PHP_INT_MAX, 323927832, 174623748237, PHP_INT_MAX.PHP_INT_MAX);
    foreach ($a as $key) {
        $converted=gmp_convert($key,10,36);
        $phpstandard=base_convert($key,10,36);
        print 'key='.$key.'. Convert: '.$phpstandard.','.$converted;
        if (!(base_convert($phpstandard,36,10)==$key)) { print '<strong>Standard PHP Failed</strong>'; }
        if (!(gmp_convert($converted,36,10)==$key)) { print '<strong>GM PHP Failed</strong>'; }
        print '<br>';
    }
    foreach ($a as $skey) {
        $key=md5($skey);
        $converted=gmp_convert($key,16,36);
        $phpstandard=base_convert($key,16,36);
        print 'key='.$key.'. Convert: '.$phpstandard.','.$converted;
        if (!(base_convert($phpstandard,36,16)==$key)) { print '  <strong>Standard PHP Failed</strong>'; }
        if (!(gmp_convert($converted,36,16)==$key)) { print '  <strong>GM PHP Failed</strong>'; }
        print '<br>';
    }
}