Skip to content

Instantly share code, notes, and snippets.

@rudiedirkx
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rudiedirkx/31aa33a568881b83e088 to your computer and use it in GitHub Desktop.
Save rudiedirkx/31aa33a568881b83e088 to your computer and use it in GitHub Desktop.
<?php
// Helpers
$space = function($hex) {
return implode(' ', str_split($hex, 2));
};
$debug = function($dec) use ($space) {
echo 'dec: ' . $dec . "\n";
echo 'hex: ' . $space(dec2hex($dec)) . "\n\n";
};
// Cases
$_time = microtime(1);
$debug('2000'); // 2k
$debug('1000000'); // 1M
$debug('99999999'); // 100M
$debug('120045041395046077749311747456482878735'); // 12BBBB
// gmp is twice as fast as bc, but bc always works
echo number_format((microtime(1) - $_time) * 1000, 3) . "ms\n";
// Magic
function dec2hex($dec) {
$bytes = 1;
while (gmp_cmp(gmp_pow(256, $bytes), $dec) <= 0) {
#while (bccomp(bcpow(256, $bytes), $dec) <= 0) {
$bytes++;
}
$left = gmp_init($dec);
#$left = $dec;
$bin = '';
for ($byte = $bytes; $byte > 0; $byte--) {
$range = gmp_pow(256, $byte-1);
#$range = bcpow(256, $byte-1);
$n = gmp_div($left, $range);
#$n = bcdiv($left, $range, 0);
$left = gmp_sub($left, gmp_mul($range, $n));
#$left = bcsub($left, bcmul($range, $n));
$bin .= chr(gmp_strval($n));
#$bin .= chr($n);
}
return bin2hex($bin);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment