2024 PHP Conference Japan

base_convert

(PHP 4, PHP 5, PHP 7, PHP 8)

base_convert在任意進位制之間轉換數字

說明

base_convert(字串 $num, 整數 $from_base, 整數 $to_base): 字串

傳回一個以 $to_base 基底表示 $num 的字串。 $num 的原始基底由 $from_base 指定。$from_base$to_base 都必須介於 2 到 36 之間(含)。基底大於 10 的數字將以字母 a-z 表示,其中 a 代表 10,b 代表 11,z 代表 35。字母的大小寫無關緊要,即 $num 的解讀不區分大小寫。

警告

由於內部使用的 浮點數 類型的特性,base_convert() 在處理大數字時可能會損失精度。請參閱手冊中的浮點數章節以獲取更具體的資訊和限制。

參數

num

要轉換的數字。 $num 中的任何無效字元都會被忽略。從 PHP 7.4.0 開始,提供任何無效字元已被棄用。

from_base

$num 的原始基底

to_base

要將 $num 轉換成的基底

回傳值

轉換為 $to_base 基底的 $num

更新日誌

版本 說明
7.4.0 傳遞無效字元現在會產生棄用通知。結果仍會像無效字元不存在一樣計算。

範例

範例 #1 base_convert() 範例

<?php
$hexadecimal
= 'a37334';
echo
base_convert($hexadecimal, 16, 2);
?>

以上範例會輸出

101000110111001100110100

參見

新增註解

使用者貢獻的註解 26 則註解

PHPCoder at niconet2k dot com
13 年前
將任意大的數字從任何基底轉換為任何基底。

string convBase(string $numberInput, string $fromBaseInput, string $toBaseInput)
$numberInput 要轉換的數字,以字串表示
$fromBaseInput 要轉換的數字的基底,以字串表示
$toBaseInput 數字應轉換成的基底,以字串表示
$fromBaseInput 和 $toBaseInput 的範例
十六進位 (Base16) 的 '0123456789ABCDEF'
十進位 (Base10) 的 '0123456789'
八進位 (Base8) 的 '01234567'
二進位 (Base2) 的 '01'
您可以實際輸入任何內容,第一個字元是 0。
範例

<?php
convBase
('123', '0123456789', '01234567');
//Convert '123' from decimal (base10) to octal (base8).
//result: 173

convBase('70B1D707EAC2EDF4C6389F440C7294B51FFF57BB', '0123456789ABCDEF', '01');
//Convert '70B1D707EAC2EDF4C6389F440C7294B51FFF57BB' from hexadecimal (base16) to binary (base2).
//result:
//111000010110001110101110000011111101010110000101110
//110111110100110001100011100010011111010001000000110
//001110010100101001011010100011111111111110101011110
//111011

convBase('1324523453243154324542341524315432113200203012', '012345', '0123456789ABCDEF');
//Convert '1324523453243154324542341524315432113200203012' from senary (base6) to hexadecimal (base16).
//result: 1F9881BAD10454A8C23A838EF00F50

convBase('355927353784509896715106760','0123456789','Christopher');
//Convert '355927353784509896715106760' from decimal (base10) to undecimal (base11) using "Christopher" as the numbers.
//result: iihtspiphoeCrCeshhorsrrtrh

convBase('1C238Ab97132aAC84B72','0123456789aAbBcCdD', '~!@#$%^&*()');
//Convert'1C238Ab97132aAC84B72' from octodecimal (base18) using '0123456789aAbBcCdD' as the numbers to undecimal (base11) using '~!@#$%^&*()' as the numbers.
//result: !%~!!*&!~^!!&(&!~^@#@@@&

function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
if (
$fromBaseInput==$toBaseInput) return $numberInput;
$fromBase = str_split($fromBaseInput,1);
$toBase = str_split($toBaseInput,1);
$number = str_split($numberInput,1);
$fromLen=strlen($fromBaseInput);
$toLen=strlen($toBaseInput);
$numberLen=strlen($numberInput);
$retval='';
if (
$toBaseInput == '0123456789')
{
$retval=0;
for (
$i = 1;$i <= $numberLen; $i++)
$retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
return
$retval;
}
if (
$fromBaseInput != '0123456789')
$base10=convBase($numberInput, $fromBaseInput, '0123456789');
else
$base10 = $numberInput;
if (
$base10<strlen($toBaseInput))
return
$toBase[$base10];
while(
$base10 != '0')
{
$retval = $toBase[bcmod($base10,$toLen)].$retval;
$base10 = bcdiv($base10,$toLen,0);
}
return
$retval;
}
?>
ardavies at tiscali dot co dot uk
10 年前
為了將僅包含英數字元 (A-Z) 的 26 進位(二十六進位),不含整數,(如 http://en.wikipedia.org/wiki/Hexavigesimal 中所述)進行轉換,我發現這很有用

函式 base_convert_alpha( $str, $from, $to )
{
$r = range( 'A', 'Z' );
$clean = str_replace( $r, array_keys($r), $str );
return base_convert( $clean, $from, $to );
}

echo base_convert_alpha( "BAC", 26, 10 );

//$clean = 102,然後回傳 678
匿名
6 年前
雖然上述說明沒有立即闡明,但負號也會被「默默地忽略」。

base_convert("-12", 10, 10) => 12
Clifford dot ct at gmail dot com
12 年前
如果您使用 base_convert 將一個很大的(例如 80 位元)十六進位制數字轉換為 36 進位制,您可能會觀察到

ABCDEF00001234567890 (十六進位制) => 3O47RE02JZSW0KS8 (36 進位制) => ABCDEF00001240000000 (十六進位制)

這是正常現象,是由於大型數字的精度損失造成的。

我已經使用內建的 BC Math 擴充套件編寫了一個基於字串的函式,它可以克服這個問題以及類似的問題。

<?php

函式 str_baseconvert($str, $frombase=10, $tobase=36) {
$str = trim($str);
如果(intval($frombase) != 10) {
$len = strlen($str);
$q = 0;
對於( $i=0; $i<$len; $i++) {
$r = base_convert($str[$i], $frombase, 10);
$q = bcadd(bcmul($q, $frombase), $r);
}
}
否則 $q = $str;

如果(intval($tobase) != 10) {
$s = '';
(bccomp($q, '0', 0) > 0) {
$r = intval(bcmod($q, $tobase));
$s = base_convert($r, 10, $tobase) . $s;
$q = bcdiv($q, $tobase, 0);
}
}
否則 $s = $q;

回傳 $s;
}

?>

典型用例
1. 將任意精度的巨大數字轉換為 36 進位。
2. 將 32 個字元的十六進位 UUID (128 位元) 轉換為 25 個字元的 36 進位唯一鍵,反之亦然。

範例

<?php
$b16
= 'ABCDEF00001234567890';
$b36 = str_baseconvert($b16, 16, 36);
echo (
"$b16 (十六進位) = $b36 (36進位) \\n");

$uuid = 'ABCDEF01234567890123456789ABCDEF';
$ukey = str_baseconvert($uuid, 16, 36);
echo (
"$uuid (十六進位) = $ukey (36進位) \\n");
?>

ABCDEF00001234567890 (十六進位) = 3o47re02jzqisvio (36進位)
ABCDEF01234567890123456789ABCDEF (十六進位) = a65xa07491kf5zyfpvbo76g33 (36進位)
JR
13 年前
簡短的阿拉伯數字轉羅馬數字轉換器

<?php
function rome($N){
$c='IVXLCDM';
for(
$a=5,$b=$s='';$N;$b++,$a^=7)
for(
$o=$N%$a,$N=$N/$a^0;$o--;$s=$c[$o>2?$b+$N-($N&=-2)+$o=1:$b].$s);
return
$s;
}
?>

而且它可以運作 :)
lindsay at bitleap dot com
19 年前
如果您需要使用 base_convert 處理大於 32 位元的數字,以下使用 gmp 實作的 base_convert 應該可以運作。

<?php

/*使用 gmp 函式庫來轉換進位。 gmp 可以轉換大於 32 位元的數字*/
function gmp_convert($num, $base_a, $base_b)
{
return
gmp_strval ( gmp_init($num, $base_a), $base_b );
}

?>
Theriault
15 年前
如果您想將數字轉換為僅使用大寫字母的進位制,反之亦然(例如 Microsoft Windows Excel 工作表中的欄名...A-Z、AA-ZZ、AAA-ZZZ...),以下函式可以做到這一點。

<?php

/**
* 將整數轉換為字母基底 (A-Z)。
*
* @param int $n 要轉換的數字。
* @return string 轉換後的數字。
* @author Theriault
*
*/
function num2alpha($n) {
$r = '';
for (
$i = 1; $n >= 0 && $i < 10; $i++) {
$r = chr(0x41 + ($n % pow(26, $i) / pow(26, $i - 1))) . $r;
$n -= pow(26, $i);
}
return
$r;
}
/**
* 將字母字串轉換為整數。
*
* @param int $n 要轉換的數字。
* @return string 轉換後的數字。
* @author Theriault
*
*/
function alpha2num($a) {
$r = 0;
$l = strlen($a);
for (
$i = 0; $i < $l; $i++) {
$r += pow(26, $i) * (ord($a[$l - $i - 1]) - 0x40);
}
return
$r - 1;
}

?>

Microsoft Windows Excel 的字母編碼在 IV (255) 就停止了,但這個函式可以處理更大的數字。然而,一段時間後會開始形成英文單字,有些可能具有冒犯性,所以請小心使用。
AdamJacobMuller at AdamJacobMuller dot com
20 年前
<?php
function binarycodedstring2dec($binary) {
$len=strlen($binary);
$rows=($len/4)-1;
if ((
$len%4)>0) {
$pad=$len+(4-($len%4));
$binary=str_pad($binary,$pad,"0",STR_PAD_LEFT);
$len=strlen($binary);
$rows=($len/4)-1;
}
$x=0;
for (
$x=0;$x<=$rows;$x++) {
$s=($x*4);
$bins=$binary[$s].$binary[$s+1].$binary[$s+2].$binary[$s+3];
$num=base_convert($bins,2,10);
if (
$num>9) {
die(
"the string is not a proper binary coded decimal\n");
} else {
$res.=$num;
}
}
return
$res;
}
?>

二進制編碼的十進制數是透過從十進制字串中取出四位數一組來轉換的,
例如,二進制編碼的十進制字串
1000 = 8
10001000 不等於 136 而是 88
所以
binarycodedstring2dec(1000) = 8
binarycodedstring2dec(11100000111001)=3839
binarycodedstring2dec(100000111001)=839

我真的不知道這個函數對任何人有沒有用,我只是因為物理期中考沒過,因為我不知道這個,所以我寫了這個函數來確保我永遠不會忘記如何轉換二進制編碼的十進制數。
xdv43 at yandex dot ru
2 年前
在沒有 PHP Math 擴展的情況下將大整數轉換為十六進制。

<?php
/*
* 建立者:Michael Renner,2006 年 5 月 17 日 03:24
*/
function baseConvert($numstring, $frombase, $tobase)
{

$chars = "0123456789abcdefghijklmnopqrstuvwxyz";
$tostring = substr($chars, 0, $tobase);

$length = strlen($numstring);
$result = '';
for (
$i = 0; $i < $length; $i++)
{
$number[$i] = strpos($chars, $numstring[$i]);
}
do
{
$divide = 0;
$newlen = 0;
for (
$i = 0; $i < $length; $i++)
{
$divide = $divide * $frombase + $number[$i];
if (
$divide >= $tobase)
{
$number[$newlen++] = (int)($divide / $tobase);
$divide = $divide % $tobase;
} elseif (
$newlen > 0)
{
$number[$newlen++] = 0;
}
}
$length = $newlen;
$result = $tostring[$divide] . $result;
} while (
$newlen != 0);
return
$result;
}
tika dot pahadi at selu dot edu
8 年前
請注意,此方法最多只能轉換 1024 位長的數字。大多數人不需要這麼做,但我曾經遇到一個問題,需要將二進位字串轉換為字母數字。在這種情況下,您需要將它們分割、轉換,然後再合併。
cyrilbele at yahoo dot fr
15 年前
如果您想進行分片,則在某些時候您需要決定要將資料分配到哪個分片。以下是一個簡單的函式,可根據鍵值(通常是資料列的識別碼)將資料分配給特定分片。

以下是一個簡單的函式,用於根據鍵值和可用的分片數量來取得分片。

<?php
function getShard($key,$nbShards) {
$num = substr(base_convert(sha1($key), 16, 10),4,6);
return
$num%$nbShards;
}
?>
wadelau at gmail dot com
6 年前
Base62x 提供了傳統 Base62 和/或 Base64 的替代方案。

base62x_encode / base62x_decode 未來將作為額外模組併入 PHP。

在此之前,使用者可以透過以下網址下載 PHP 額外模組:https://github.com/wadelau/Base62x
ohcc at 163 dot com
7 年前
<?php
$v
= base_convert(3.14, 10, 10);
var_dump($v);
?>

輸出:字串(3) "314"
simon at simonster dot com
20 年前
以下是一些用於在整數和 256 進位之間進行轉換的函式。有了這些函式,轉換成 64 進位就變得簡單了。

<?php
函式 to_base256($number, $from_base = 10) {
$binary_number = base_convert($number, $from_base, 2);
$final_string = "";
$new_length = (ceil(strlen($binary_number)/8)*8);
$binary_number = str_pad($binary_number, $new_length, "0", STR_PAD_LEFT);
for(
$i=($new_length-8); $i>=0; $i-=8) {
$final_string = chr(base_convert(substr($binary_number, $i, 8), 2, 10)).$final_string;
}
return
$final_string;
}

函式
from_base256($string, $to_base = 10) {
$number = "";
for(
$i=0; $i<strlen($string); $i++) {
$number .= str_pad(base_convert(ord($string{$i}), 10, 2), 8, "0", STR_PAD_LEFT);
}
return
base_convert($number, 2, $to_base);
}
?>

是的,我知道如果使用 mod 而不是 base_convert 會更有效率,但它需要處理大於 32 位元的整數。
denik dot od at gmail dot com
11 年前
將任意長度的位元轉換為十六進位

函式 bits2hex($bin)
{
$out = "";
for($i=0;$i<strlen($bin);$i+=8)
{
$byte = substr($bin,$i,8); if( strlen($byte)<8 ) $byte .= str_repeat('0',8-strlen($byte));
$out .= base_convert($byte,2,16);
}
return $out;
}

警告!如果最後一個位元組不完整,它會以字串形式用零補足!
匿名
6 年前
其他一些沒有錯誤捕捉的 base32 迷你實作。只是將資料從 5 位元轉換到 8 位元,以及從 8 位元轉換到 5 位元。mho 敬上。

<?
函式 base32_decode($d)
{
list($t, $b, $r) = array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "", "");

將 $d 字串分割成單個字元,並逐一迭代
將 $c 在 $t 字串中的位置轉換為 5 位二進位制字串,並附加到 $b

將 $b 字串以 8 位為一組分割,並逐一迭代
將 $c 的二進位制字串轉換為十進位制數字,再轉換為 ASCII 字元,並附加到 $r

回傳 $r
}

Base32 編碼函式
{
list($t, $b, $r) = array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "", "");

將 $d 字串分割成單個字元,並逐一迭代
將 $c 的 ASCII 碼轉換為 8 位二進位制字串,並附加到 $b

將 $b 字串以 5 位為一組分割,並逐一迭代
將 $c 的二進位制字串轉換為十進位制數字,再以此數字作為索引取得 $t 字串中的字元,並附加到 $r

回傳 $r
}
?>
fiftytoo at buckeyeexpress dot com
20 年前
我需要一個函式來反轉十六進位值,用於在彩色背景上設定字體顏色,這樣可以得到對比色。

我相信還有其他使用這個函式的理由,由您決定!

<?php
函式 InvertColor($hex) {
return
sprintf("%06s",base_convert(($hex ^ 0xFFFFFF),10,16));
};

print
'<td bgcolor="BB2222"><font color="'.InvertColor(0xBB2222).'">Blah</font></td>';
// 輸出 44dddd 作為字體顏色,這是它在色輪上的相反顏色

?>
CJ Dennis
18 年前
非常大的數字可能會在兩端被截斷。
例如
<?php
$binary
="...略...";
print(
strtoupper(base_convert($binary, 2, 16)));
?>
將輸出
9E8EA23CB63C0000000000000000000000000000000000000000000000000000 (64 個十六進位數字)
當正確的結果應該是
6A9E8EA23CB63C228F31AD9268B4097F156D6AA11DCB29F14BACCFF196CE3F0AD2 (66 個十六進位數字)
請注意,除了 B63C 之後的結果顯示為 '0'(這是預期的)之外,它還缺少 9E 之前的 6A。
tecdoc at ukr dot net
1 年前
補充 "lindsay at bitleap dot com" 建議的方法。

在 32 位元版本的 PHP 中,將十六進位制字串轉換為十進位制字串的簡單方法
<?php
$test
= '0x7000005a00000ea5';
$rrrrr = gmp_strval($test);
var_dump($test, $rrrrr);
?>
將回傳
//string '0x7000005a00000ea5' (length=18)
//string '8070450918794989221' (length=19)

base_convert 將回傳 8070450918794990488
bryan at bryanruiz dot com
13 年前
符合 RFC 4648 標準的 Base32 編碼。如果您最終使用位元運算或其他方法提高了效率,請發送電子郵件給我。

<?php

/**
* Encode in Base32 based on RFC 4648.
* Requires 20% more space than base64
* Great for case-insensitive filesystems like Windows and URL's (except for = char which can be excluded using the pad option for urls)
*
* @package default
* @author Bryan Ruiz
**/
class Base32 {

private static
$map = array(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 7
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
'=' // padding char
);

private static
$flippedMap = array(
'A'=>'0', 'B'=>'1', 'C'=>'2', 'D'=>'3', 'E'=>'4', 'F'=>'5', 'G'=>'6', 'H'=>'7',
'I'=>'8', 'J'=>'9', 'K'=>'10', 'L'=>'11', 'M'=>'12', 'N'=>'13', 'O'=>'14', 'P'=>'15',
'Q'=>'16', 'R'=>'17', 'S'=>'18', 'T'=>'19', 'U'=>'20', 'V'=>'21', 'W'=>'22', 'X'=>'23',
'Y'=>'24', 'Z'=>'25', '2'=>'26', '3'=>'27', '4'=>'28', '5'=>'29', '6'=>'30', '7'=>'31'
);

/**
* Use padding false when encoding for urls
*
* @return base32 encoded string
* @author Bryan Ruiz
**/
public static function encode($input, $padding = true) {
if(empty(
$input)) return "";
$input = str_split($input);
$binaryString = "";
for(
$i = 0; $i < count($input); $i++) {
$binaryString .= str_pad(base_convert(ord($input[$i]), 10, 2), 8, '0', STR_PAD_LEFT);
}
$fiveBitBinaryArray = str_split($binaryString, 5);
$base32 = "";
$i=0;
while(
$i < count($fiveBitBinaryArray)) {
$base32 .= self::$map[base_convert(str_pad($fiveBitBinaryArray[$i], 5,'0'), 2, 10)];
$i++;
}
if(
$padding && ($x = strlen($binaryString) % 40) != 0) {
if(
$x == 8) $base32 .= str_repeat(self::$map[32], 6);
else if(
$x == 16) $base32 .= str_repeat(self::$map[32], 4);
else if(
$x == 24) $base32 .= str_repeat(self::$map[32], 3);
else if(
$x == 32) $base32 .= self::$map[32];
}
return
$base32;
}

public static function
decode($input) {
if(empty(
$input)) return;
$paddingCharCount = substr_count($input, self::$map[32]);
$allowedValues = array(6,4,3,1,0);
if(!
in_array($paddingCharCount, $allowedValues)) return false;
for(
$i=0; $i<4; $i++){
if(
$paddingCharCount == $allowedValues[$i] &&
substr($input, -($allowedValues[$i])) != str_repeat(self::$map[32], $allowedValues[$i])) return false;
}
$input = str_replace('=','', $input);
$input = str_split($input);
$binaryString = "";
for(
$i=0; $i < count($input); $i = $i+8) {
$x = "";
if(!
in_array($input[$i], self::$map)) return false;
for(
$j=0; $j < 8; $j++) {
$x .= str_pad(base_convert(@self::$flippedMap[@$input[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
}
$eightBits = str_split($x, 8);
for(
$z = 0; $z < count($eightBits); $z++) {
$binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:"";
}
}
return
$binaryString;
}
}
liams dot test dot acc at gmail dot com
9 年前
這是我大學作業的一部分,用於縮短網址。它適用於任何基數和任何字元範圍,例如 A-Za-z0-9 等等。希望它能幫助到某些人。

<?php

$base
= range(0, 1);
$number = 255;

function
translate($base, $number){

$array = array();
$n = count($base);
$i = $number;

while(
true){

/* 透過 $i % $n 我們可以得到數字除以基數後的餘數。
* 從 $i(數字)中減去結果,再除以 $n(基數),
* 我們將結果重新賦值給 $i,從而移至下一個最小的指數,
* 並再次循環。它繼續這樣做,產生餘數,直到 $i <= 0,
* 此時它會中斷。
*/

if($i <= 0){

break;
}else{
$r = ($i % $n);

//重新賦值 $i
$i = ($i - $r) / $n;

$array[] = $base[$r];
}
}
$string = implode("", $array);
return
$string;
}

$string = translate($base, $number);
echo
$string;

// 顯示 11111111
?
andrew at youritland dot co dot uk
10 年前
使用 base_convert 產生隨機密碼的範例

function random_password()
{
$rvalue1 = mt_rand(100,999);
$rvalue2 = time();
$rvalue3 = mt_rand(1000,9999);
$rvalue4 = mt_rand(1,9);
$rvalue5 = mt_rand(101,109);
//組合數值
$rvalues = intval(((($rvalue2.$rvalue3) + $rvalue1)*$rvalue4) / $rvalue5);

//以 35 進位回傳數值 (將包含 '0' 到 'z' 的字元)
return base_convert($rvalues,10,35);
}

更改 rvalue5 的範圍以獲得更多或更少的字元。此設定
將回傳 8 個字元。
bpds
13 年前
一個將整數轉換為任何進位的簡單函式。

<?php
函式 intToAlphaBaseN($n,$baseArray) {
$l=count($baseArray);
$s = '';
for (
$i = 1; $n >= 0 && $i < 10; $i++) {
$s = $baseArray[($n % pow($l, $i) / pow($l, $i - 1))].$s;
$n -= pow($l, $i);
}
return
$s;
}

$alpha=array('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');
$r=rand(0, 99999999999);
echo(
intToAlphaBaseN($r,$alpha));
?>
Ray Paseur 有時會使用 Gmail
17 年前
[danbrown AT php DOT net 編輯:此函式提供阿拉伯數字(世界上大多數人使用的標準數字 1,2,3,4,...)轉換為羅馬數字(I,II,III,IV,...)。原作者沒有提供說明,但由於此函式的實用性,它被保留下來,並添加了簡短說明。]

<?php
function roman_numerals($input_arabic_numeral='') {

if (
$input_arabic_numeral == '') { $input_arabic_numeral = date("Y"); } // DEFAULT OUTPUT: THIS YEAR
$arabic_numeral = intval($input_arabic_numeral);
$arabic_numeral_text = "$arabic_numeral";
$arabic_numeral_length = strlen($arabic_numeral_text);

if (!
ereg('[0-9]', $arabic_numeral_text)) {
return
false; }

if (
$arabic_numeral > 4999) {
return
false; }

if (
$arabic_numeral < 1) {
return
false; }

if (
$arabic_numeral_length > 4) {
return
false; }

$roman_numeral_units = $roman_numeral_tens = $roman_numeral_hundreds = $roman_numeral_thousands = array();
$roman_numeral_units[0] = $roman_numeral_tens[0] = $roman_numeral_hundreds[0] = $roman_numeral_thousands[0] = ''; // NO ZEROS IN ROMAN NUMERALS

$roman_numeral_units[1]='I';
$roman_numeral_units[2]='II';
$roman_numeral_units[3]='III';
$roman_numeral_units[4]='IV';
$roman_numeral_units[5]='V';
$roman_numeral_units[6]='VI';
$roman_numeral_units[7]='VII';
$roman_numeral_units[8]='VIII';
$roman_numeral_units[9]='IX';

$roman_numeral_tens[1]='X';
$roman_numeral_tens[2]='XX';
$roman_numeral_tens[3]='XXX';
$roman_numeral_tens[4]='XL';
$roman_numeral_tens[5]='L';
$roman_numeral_tens[6]='LX';
$roman_numeral_tens[7]='LXX';
$roman_numeral_tens[8]='LXXX';
$roman_numeral_tens[9]='XC';

$roman_numeral_hundreds[1]='C';
$roman_numeral_hundreds[2]='CC';
$roman_numeral_hundreds[3]='CCC';
$roman_numeral_hundreds[4]='CD';
$roman_numeral_hundreds[5]='D';
$roman_numeral_hundreds[6]='DC';
$roman_numeral_hundreds[7]='DCC';
$roman_numeral_hundreds[8]='DCCC';
$roman_numeral_hundreds[9]='CM';

$roman_numeral_thousands[1]='M';
$roman_numeral_thousands[2]='MM';
$roman_numeral_thousands[3]='MMM';
$roman_numeral_thousands[4]='MMMM';

if (
$arabic_numeral_length == 3) { $arabic_numeral_text = "0" . $arabic_numeral_text; }
if (
$arabic_numeral_length == 2) { $arabic_numeral_text = "00" . $arabic_numeral_text; }
if (
$arabic_numeral_length == 1) { $arabic_numeral_text = "000" . $arabic_numeral_text; }

$anu = substr($arabic_numeral_text, 3, 1);
$anx = substr($arabic_numeral_text, 2, 1);
$anc = substr($arabic_numeral_text, 1, 1);
$anm = substr($arabic_numeral_text, 0, 1);

$roman_numeral_text = $roman_numeral_thousands[$anm] . $roman_numeral_hundreds[$anc] . $roman_numeral_tens[$anx] . $roman_numeral_units[$anu];
return (
$roman_numeral_text);
}
?>
Baji dot Panchumarti at gmail dot com
12 年前
將 base_convert 擴展到 36 以上的進位制,最高到 62 進位。

<?php
function base_convert_x( $_number='', $_frBase=10, $_toBase=62 ) {

# Today's Date - C74 - convert a string (+ve integer) from any arbitrary base to any arbitrary base, up to base 62, using 0-9,A-Z,a-z
#
# Usage : echo base_convert_x( 123456789012345, 10, 32 );

$_10to62 = array(
'0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '00' => '0', '01' => '1', '02' => '2', '03' => '3', '04' => '4', '05' => '5', '06' => '6', '07' => '7',
'10' => 'A', '11' => 'B', '12' => 'C', '13' => 'D', '14' => 'E', '15' => 'F', '16' => 'G', '17' => 'H', '18' => 'I', '19' => 'J', '20' => 'K', '21' => 'L', '22' => 'M', '23' => 'N', '24' => 'O', '25' => 'P', '26' => 'Q', '27' => 'R',
'30' => 'U', '31' => 'V', '32' => 'W', '33' => 'X', '34' => 'Y', '35' => 'Z', '36' => 'a', '37' => 'b', '38' => 'c', '39' => 'd', '40' => 'e', '41' => 'f', '42' => 'g', '43' => 'h', '44' => 'i', '45' => 'j', '46' => 'k', '47' => 'l',
'50' => 'o', '51' => 'p', '52' => 'q', '53' => 'r', '54' => 's', '55' => 't', '56' => 'u', '57' => 'v', '58' => 'w', '59' => 'x', '60' => 'y', '61' => 'z' );

$_62to10 = array(
'0' => '00', '1' => '01', '2' => '02', '3' => '03', '4' => '04', '5' => '05', '6' => '06', '7' => '07', '8' => '08', '9' => '09', 'A' => '10', 'B' => '11', 'C' => '12', 'D' => '13', 'E' => '14', 'F' => '15', 'G' => '16', 'H' => '17',
'K' => '20', 'L' => '21', 'M' => '22', 'N' => '23', 'O' => '24', 'P' => '25', 'Q' => '26', 'R' => '27', 'S' => '28', 'T' => '29', 'U' => '30', 'V' => '31', 'W' => '32', 'X' => '33', 'Y' => '34', 'Z' => '35', 'a' => '36', 'b' => '37',
'e' => '40', 'f' => '41', 'g' => '42', 'h' => '43', 'i' => '44', 'j' => '45', 'k' => '46', 'l' => '47', 'm' => '48', 'n' => '49', 'o' => '50', 'p' => '51', 'q' => '52', 'r' => '53', 's' => '54', 't' => '55', 'u' => '56', 'v' => '57',
'y' => '60', 'z' => '61' );

# ---- First convert from frBase to base-10

$_in_b10 = 0;
$_pwr_of_frB = 1; # power of from base, eg. 1, 8, 64, 512
$_chars = str_split( $_number ); # split input # into chars
$_str_len = strlen( $_number );
$_pos = 0;

while (
$_pos++ < $_str_len ) {
$_char = $_chars[$_str_len - $_pos];
$_in_b10 += (((int) $_62to10[$_char] ) * $_pwr_of_frB);
$_pwr_of_frB *= $_frBase;
}

# ---- Now convert from base-10 to toBase

$_dividend = (int) $_in_b10; # name dividend easier to follow below
$_in_toB = ''; # number string in toBase

while ( $_dividend > 0 ) {

$_quotient = (int) ( $_dividend / $_toBase ); # eg. 789 / 62 = 12 ( C in base 62 )
$_remainder = '' . ( $_dividend % $_toBase ); # 789 % 62 = 45 ( j in base 62 )
$_in_toB = $_10to62[$_remainder] . $_in_toB; # 789 (in base 10) = Cj (in base 62)
$_dividend = $_quotient; # new dividend is the quotient from base division
}

if (
$_in_toB == '' )
$_in_toB = '0';

return
$_in_toB; # base $_toBase string
}
# --------- examples -------
echo base_convert_x( '3456789ABCDEF', 16, 10 ) . "\n"; # 920735923817967
echo base_convert( '3456789ABCDEF', 16, 10 ) . "\n"; # 920735923817967
?>
francesco[at]paladinux.net
14 年前
base_convert 對於標準進位制的支援有限。
在某些情況下,如果您想創造一些轉換程式碼(例如授權碼),我希望這個 base_convert-AS 的例子,從十進位轉換為 65 進位以產生快速碼,對您有所幫助。
更具體地說:您可以使用資料庫進行轉換
$speedCodeDEC = $idAziendaMittente.$idAziendaDestinatario.$idDDT ;

//$speedCodeDEC = 3000;

//
$BASECODE = array();
$BASECODE['items'] = 65;
$BASECODE[1]='1';
$BASECODE[2]='2';
$BASECODE[3] = '3';
$BASECODE[4] = '4';
....
$BASECODE[10] = 'a';
$BASECODE[11] = 'b';
$BASECODE[12] = 'c';
...
$BASECODE[36] = 'A';
$BASECODE[37] = 'B';
$BASECODE[38] = 'C';
...
$BASECODE[61] = 'Z';
$BASECODE[62] = '/';
$BASECODE[63] = '-';
$BASECODE[64] = '+';
//

//print_r ($BASECODE); 測試

function creaSpeedCode($speedCodeDEC, $partialCode = "", $BASECODE) {

@$division = $speedCodeDEC / $BASECODE['items'];
@$resultINT = floor($speedCodeDEC / $BASECODE['items']);
@$remnant = $speedCodeDEC % $BASECODE['items'];
$partialCode = $BASECODE[$remnant] . $partialCode;
echo "
<br>
輸入 speedCodeDEC: $speedCodeDEC - partialCode: $partialCode<br>
items : " . $BASECODE['items'] . "<br>
division : $division <br>
resultINT : $resultINT <br>
remnant : $remnant <br>
partialCode : $partialCode <br>
"; //測試
if ($resultINT > 65) $partialCode = creaSpeedCode($resultINT, $partialCode, $BASECODE);
return $BASECODE[$resultINT] . $partialCode;
}
echo $speedCodeDEC . "<br>";
echo $risultato = creaSpeedCode($speedCodeDEC, "", $BASECODE);
To Top