字符串編碼流程
- 將字符串的每個(gè)字節(jié)換算成ASCII(0-255) (字符串實(shí)際上就是256進(jìn)制的數(shù)字組合)
- 源字符串為:ABD
- 換算后: 65 66 68
- 將256進(jìn)制的數(shù)字轉(zhuǎn)換成10進(jìn)制數(shù)字
- 256進(jìn)制數(shù):65 66 68
- 轉(zhuǎn)成10進(jìn)制:(65 * 256 + 66) * 256 + 68 = 4276804
- 將10進(jìn)制數(shù)字轉(zhuǎn)換成58進(jìn)制數(shù)字
- 10進(jìn)制數(shù):4276804
- 58進(jìn)制數(shù): 21 53 20 0
- 將58進(jìn)制數(shù)字的每一位按照表格轉(zhuǎn)換成對(duì)應(yīng)的字符
- 58進(jìn)制數(shù):21 53 20 0
- 碼表:123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ
- 轉(zhuǎn)換后的字符:nVm1
字符串解碼流程
- 字符串每一位按碼表替換成數(shù)字 (58進(jìn)制)
- 源字符: nVm1
- 58進(jìn)制數(shù):21 53 20 0
- 58進(jìn)制轉(zhuǎn)10進(jìn)制
- 58進(jìn)制數(shù):21 53 20 0
- 10進(jìn)制數(shù):4276804
- 10進(jìn)制轉(zhuǎn)256進(jìn)制
- 10進(jìn)制數(shù):4276804
- 256進(jìn)制: 65 66 68
- 256進(jìn)制轉(zhuǎn)字符(按ascii轉(zhuǎn))
- 256進(jìn)制: 65 66 68
- 字符:ABD
總結(jié):
- 編碼流程:將ascii編碼的字符串(256進(jìn)制)宛裕,轉(zhuǎn)換成58進(jìn)制。然后按照58進(jìn)制的碼表轉(zhuǎn)換成相應(yīng)的字符。
- 解碼流程:按碼表把字符轉(zhuǎn)成58進(jìn)制數(shù)字牺蹄,再轉(zhuǎn)256進(jìn)制,按ascii把256進(jìn)制數(shù)字轉(zhuǎn)字符
注:任意進(jìn)制之間的轉(zhuǎn)換薄翅,先將數(shù)字轉(zhuǎn)10進(jìn)制再轉(zhuǎn)其它進(jìn)制
附:php代碼一份
<?php
$encode = base58_encode('ABD');
echo "\n".$encode;
$decode = base58_decode($encode);
echo "\n".$decode;
function base58_encode($string)
{
$alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
$base = strlen($alphabet);
if (is_string($string) === false || !strlen($string)) {
return false;
}
$bytes = array_values(unpack('C*', $string));
$decimal = $bytes[0];
for ($i = 1, $l = count($bytes); $i < $l; ++$i) {
$decimal = bcmul($decimal, 256);
$decimal = bcadd($decimal, $bytes[$i]);
}
$output = '';
while ($decimal >= $base) {
$div = bcdiv($decimal, $base, 0);
$mod = bcmod($decimal, $base);
$output .= $alphabet[$mod];
$decimal = $div;
}
if ($decimal > 0) {
$output .= $alphabet[$decimal];
}
$output = strrev($output);
return (string) $output;
}
function base58_decode($base58)
{
$alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
$base = strlen($alphabet);
if (is_string($base58) === false || !strlen($base58)) {
return false;
}
$indexes = array_flip(str_split($alphabet));
$chars = str_split($base58);
foreach ($chars as $char) {
if (isset($indexes[$char]) === false) {
return false;
}
}
$decimal = $indexes[$chars[0]];
for ($i = 1, $l = count($chars); $i < $l; ++$i) {
$decimal = bcmul($decimal, $base);
$decimal = bcadd($decimal, $indexes[$chars[$i]]);
}
$output = '';
while ($decimal > 0) {
$byte = bcmod($decimal, 256);
$output = pack('C', $byte).$output;
$decimal = bcdiv($decimal, 256, 0);
}
return $output;
}