Inquisitive Cocoa

Unless otherwise stated all code is released under the MIT License

Entries in the Web category:

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, Web5 Responses, Add your thoughts

Categories & Tags:
By Date: