base_convert() 可在 2 到 36 進制之間任意轉換,超過十進位用 a-z 表示 10-35。回傳字串,適合大數運算與編碼處理。
string base_convert(string $number, int $frombase, int $tobase)
$number:源數值字串(不帶前綴如 0x)$frombase:源進制 (2-36)$tobase:目標進制 (2-36)<?php
// 16 進制 -> 2 進制
echo base_convert('a37334', 16, 2); // 101000110111001100110100
// 10 進制 -> 2, 8, 16
$num = '123';
echo base_convert($num, 10, 2); // 1111011
echo base_convert($num, 10, 8); // 173
echo base_convert($num, 10, 16); // 7b
// 2 進制 -> 10, 8
$bin = '100000101';
echo base_convert($bin, 2, 10); // 261
echo base_convert($bin, 2, 8); // 405
// 36 進制支援 (0-9, a-z)
echo base_convert('zz', 36, 10); // 1295 (35*36 + 35)
<?php
function toBase36($int) {
return base_convert($int, 10, 36);
}
function fromBase36($str) {
return base_convert($str, 36, 10);
}
$id = 123456789;
$short = toBase36($id); // '21i3v9'
echo $short;
echo fromBase36($short); // 123456789
gmp_* 或 bcmath 擴充。| 函數 | 適用場景 |
|---|---|
decbin/bindec | 專用 10↔2,速度較快 |
decoct/octdec | 專用 10↔8 |
dechex/hexdec | 專用 10↔16,最常用 |
base_convert | 任意進制互轉,通用性最強 |
gmp_strval | 超大整數任意進制,需 GMP 擴充 |