Skip to content

Instantly share code, notes, and snippets.

View kwhat's full-sized avatar

Alex Barker kwhat

View GitHub Profile
@kwhat
kwhat / BinaryBaseConvert.php.md
Last active March 3, 2020 22:26
Binary Base Conversion in PHP

So, I have come accorss a lot of poor PHP base conversion implementations all over the internet that are unsuitable or incapable of doing large base conversion on binary data. This really isn't a problem for most people in PHP until you start dealing with very large decimals that are sensitive to percision loss, like in cryptography. The following provides two implementations for base conversion that should be safe for large bases and binary data, for example, converting a base256 (binary string) to base85 representation and back again.

Using GMP

You can use GMP to accomplish this at the cost of converting bin<->hex two unneeded times as well as being limited to base62.

<?php
// Not bits, bytes.
$data = openssl_random_pseudo_bytes(256);