note 52450 deleted from function.base-convert by danbrown
| From: | danbrown@php.net | Date: | Sat, 02 Jul 2011 15:40:25 +0000 |
| Subject: | note 52450 deleted from function.base-convert by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-181171@lists.php.net to get a copy of this message | ||
Note Submitter: fragmer[at]mail[dot]ru
----
Here is a much simpler and faster version of the "custombase_convert" function proposed by
Mr.Fips (see below). My functions convert decimals to and from custom bases:
<?php
// Decimal > Custom
function dec2any( $num, $base=62, $index=false ) {
if (! $base ) {
$base = strlen( $index );
} else if (! $index ) {
$index = substr( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0
,$base );
}
$out = "";
for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) {
$a = floor( $num / pow( $base, $t ) );
$out = $out . substr( $index, $a, 1 );
$num = $num - ( $a * pow( $base, $t ) );
}
return $out;
}
?>
Parameters:
$num - your decimal integer
$base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if
you're using default (62))
$index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise
provide a string (ex.: "zyxwvu")
<?php
// Custom > Decimal
function any2dec( $num, $base=62, $index=false ) {
if (! $base ) {
$base = strlen( $index );
} else if (! $index ) {
$index = substr( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0,
$base );
}
$out = 0;
$len = strlen( $num ) - 1;
for ( $t = 0; $t <= $len; $t++ ) {
$out = $out + strpos( $index, substr( $num, $t, 1 ) ) * pow( $base, $len - $t );
}
return $out;
}
?>
Parameters:
$num - your custom-based number (string) (ex.: "11011101")
$base - base with which $num was encoded (leave it 0 if you are providing $index or omit if
you're using default (62))
$index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise
provide a string (ex.: "abcdef")
I have optimized the functions as much as I could, I hope they'll be helpful to someone.