Created
May 14, 2012 18:05
-
-
Save jedisct1/2695395 to your computer and use it in GitHub Desktop.
base32 encode/decode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function webigin2_base32_encode($str) { | |
| $BASE32_TABLE = '0123456789bcdfghjklmnpqrstuvwxyz'; | |
| $out = ''; | |
| $i = $v = $bits = 0; | |
| $str_len = strlen($str); | |
| while ($i < $str_len) { | |
| $v |= ord($str[$i++]) << $bits; | |
| $bits += 8; | |
| while ($bits >= 5) { | |
| $out .= $BASE32_TABLE[$v & 31]; | |
| $bits -= 5; | |
| $v >>= 5; | |
| } | |
| } | |
| if ($bits > 0) { | |
| $out .= $BASE32_TABLE[$v & 31]; | |
| } | |
| return $out; | |
| } | |
| function webigin2_base32_decode($str, $extrabits = 0) { | |
| $BASE32_TABLE = '0123456789bcdfghjklmnpqrstuvwxyz'; | |
| $str_len = strlen($str); | |
| $out = ''; | |
| $i = $v = $vbits = 0; | |
| while ($i < $str_len) { | |
| if (($x = strpos($BASE32_TABLE, $str[$i++])) == FALSE) { | |
| return FALSE; | |
| } | |
| $v |= $x << $vbits; | |
| $vbits += 5; | |
| if ($vbits >= 8) { | |
| $out .= chr($v); | |
| $v >>= 8; | |
| $vbits -= 8; | |
| } | |
| } | |
| $vbits += $extrabits; | |
| while ($vbits >= 8) { | |
| $out .= chr($v); | |
| $v >>= 8; | |
| $vbits -= 8; | |
| } | |
| return $out; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment