Skip to content

Instantly share code, notes, and snippets.

@DavidFricker
Created March 21, 2017 23:28
Show Gist options
  • Select an option

  • Save DavidFricker/5af8086450c51398bb3edae74245fddd to your computer and use it in GitHub Desktop.

Select an option

Save DavidFricker/5af8086450c51398bb3edae74245fddd to your computer and use it in GitHub Desktop.
large raw binary base conversion php
/**
Enables alphanumeric encoding and decoding of binary data for easy transportation over any medium
Works using the GMP extension to avoid PHP's base_convert loss of preceision when working with large numbers e.g. a 256 bit key
converts the binary to hex then to an arbitrary base, 62 is best in my experince
*/
class BinaryBaseChanger {
const STORAGE_BASE = 16;
public static function changeTo($binary_data, $base_to) {
$hexadecimal = bin2hex($binary_data);
return self::gmpBaseChange($hexadecimal, self::STORAGE_BASE, $base_to);
}
public static function changeFrom($encoded_hex, $base_from) {
$hexadecimal = self::gmpBaseChange($encoded_hex, $base_from, self::STORAGE_BASE);
// if its not even it will be rejected by hex2bin
// add a precceding zero if its uneven
if(strlen($hexadecimal) % 2 != 0) {
$hexadecimal = '0'.$hexadecimal;
}
return hex2bin($hexadecimal);
}
private static function gmpBaseChange($input, $base_from, $base_to) {
return gmp_strval(gmp_init($input, $base_from), $base_to);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment