首页 > 代码库 > BitCoin源码研究(1)-Base58编码

BitCoin源码研究(1)-Base58编码

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 字符


本文出自 “清澈” 博客,转载请与作者联系!

BitCoin源码研究(1)-Base58编码