Inquisitive Cocoa

Unless otherwise stated all code is released under the MIT License

While writing the PHP code to generate licenses for Eira I was surprised not to find a way to encode a string as base32. As with almost all my code it’s intentionally biased towards readability rather than efficiency.

function base32_encode($input) {
	// Get a binary representation of $input
	$binary = unpack('C*', $input);
	$binary = vsprintf(str_repeat('%08b', count($binary)), $binary);
 
	$binaryLength = strlen($binary);
	$base32_characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
	$currentPosition = 0;
	$output = '';
 
	while($currentPosition < $binaryLength) {
		$bits = substr($binary, $currentPosition, 5);
 
		if(strlen($bits) < 5)
			$bits = str_pad($bits, 5, "0");
 
		// Convert the 5 bits into a decimal number
		// and append the matching character to $output
		$output .= $base32_characters[bindec($bits)];
		$currentPosition += 5;
	}
 
	// Pad the output length to a multiple of 8 with '=' characters
	$desiredOutputLength = strlen($output);
	if($desiredOutputLength % 8 != 0) {
		$desiredOutputLength += (8 - ($desiredOutputLength % 8));
		$output = str_pad($output, $desiredOutputLength, "=");
	}
 
	return $output;
}

(MIT license)

Source, Web

5 Responses to “A base32_encode function for PHP”

  1. Steve Clay

    Does this have a license?

    • Harry

      Hi Steve,
      Sorry, only just discovered your comment (in the junk pile).. It’s probably a bit late .. but I tend to release most things under MIT license.

  2. Ryan Tamoria

    Do you have a base32_decode function for this? I would surely appreciate it if you have one…

    • Harry

      Not in PHP.. I have an Cocoa/Objective-C decoder somewhere.. I’m on a course at the moment.. will have a look.. but it’ll be in a week or so.

  3. Jack

    Here’s a base32_decode:

    http://pastebin.com/gw3gC6T7

Add your thoughts