Base58編碼由58個數字和大小寫字母組成,BitCoin源碼中定義及註釋如下:
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
如unsigned char ucData[4] = { 0x39, 0x3a, 0x3b, 0x3c };的base58編碼過程如下:
1、先計算ucData開頭爲0x00的個數 zeros ,這裏zeros = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
2、跳過開頭的zeros個0x00,計算所需要的緩存
int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up.
3、256進制轉58進制的計算
std::vector<unsigned char> b58(size);
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
int i = 0;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin();
(carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
length = i;
pbegin++;
}
4、輸出編碼結果
先在字符串前補上zeros 個1 ,後面的依次綴加DstByte對應的 pszBase58 字符