You're here: Snippet Directory » PHP (130)
Language:

Base36, Base64 or Base16 functions in PHP

Language: English
Programming Language: PHP
Published by: shanx24 [not registered]
Last Update: 5/15/2006
Views: 2751


Description

Base calculation functions implemented in PHP -- Base16, Base36 or Base64.

Code

1 <? 2 3 /** 4 * Function to calculate base36 values from a number 5 * 6 * @param $value The number 7 * @param $base The base to be applied (16, 36 or 64) 8 * @return The calculated string 9 * @author Shashank Tripathi (shanx@shanx.com) 10 * @version 0.1 - Let me know if something doesnt work 11 * 12 */ 13 14 function base36($value, $base) 15 { 16 $baseChars = array('0', '1', '2', '3', '4', '5', 17 '6', '7', '8', '9', 'a', 'b', 18 'c', 'd', 'e', 'f', 'g', 'h', 19 'i', 'j', 'k', 'l', 'm', 'n', 20 'o', 'p', 'q', 'r', 's', 't', 21 'u', 'v', 'w', 'x', 'y', 'z' 22 ); 23 24 $remainder = 0; 25 $newval = ""; 26 27 while ( $value > 0 ) 28 { 29 $remainder = $value % $base; 30 $value = ( ($value - $remainder)/ $base ); 31 $newval .= $baseChars[$remainder]; 32 } 33 return strrev($newval); 34 35 } 36 37 38 39 echo "The string for 46655, for instance, is " . base36(46655, 36); 40 41 ?>

2 comments

1

So I noticed that your function would not use the first value in the array. base36(1, 36) would return 1, not 0.

I'm not sure if this goes against all baseX protocol, but here's a function that will utilize the first value of the array:

function base36($x, $base = NULL)
{
$baseChars = array('0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
);
$newVal = '';

if(is_null($base))
$base = count($baseChars);

while($value > 0)
{
$remainder = $value % $base;
$value = (($value - $remainder) / $base);
if($remainder == 0) # if the remiander is 0, set the offset to the last item in the $chars array, and decrement $x
{
$offset = $base - $remainder;
$value--;
}
else
{
$offset = $remainder - 1;
}
$newVal .= $baseChars[$offset];
}

return strrev($newVal);

}

Monday, May 04, 2009 7:57:31 PM from db
2

>I'm not sure if this goes against all baseX protocol..

Lol! Dude, you're joking right? Sure numbering systems start with 0, but 0 and 1 are not the same. If you return 1 as 0 then you no longer have 1 do you.

If we simply your modified function down to the basics and feed it a series of 0's and 1's, this would be the result of your function:

function returnBoolean($trueorfalse)
{
return false;
}

So to anyone reading this, use the original function, not the 'omfg 1 != 0!' function.

Tuesday, January 12, 2010 8:54:19 PM from Jeck Lamnent

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS