note 52450 added to function.base-convert

From: Date: Mon, 02 May 2005 03:58:06 +0000
Subject: note 52450 added to function.base-convert
Groups: php.notes 
Request: Send a blank email to php-notes+get-88849@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/function.base-convert.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+52450 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52450&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52450&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52450&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52450&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52450&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+52450&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#88849) next »