PHP 内核源码 base64_encode

/* {{{ proto string base64_encode(string str)
   Encodes string using MIME base64 algorithm */
PHP_FUNCTION(base64_encode)
{
    char *str;
    size_t str_len;
    zend_string *result;

    ZEND_PARSE_PARAMETERS_START(1, 1)
        Z_PARAM_STRING(str, str_len)
    ZEND_PARSE_PARAMETERS_END();

    result = php_base64_encode((unsigned char*)str, str_len);
    RETURN_STR(result);
}
/* }}} */

编码过程:

  • 第一个字符 = 输入第一个字符右移 2 位
  • 第二个字符 = 输入第一个字符左移 4 位 + 输入第二个字符右移 4 位
  • 第三个字符 = 输入第一个字符左移 2 位 + 输入第三个字符右移 6 位
  • 第四个字符 = 取输入第三个字符右 6 位
/* {{{ base64 tables */
static const char base64_table[] = {
    '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',
    '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',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '\0'
};

static const char base64_pad = '=';
static zend_always_inline unsigned char *php_base64_encode_impl(const unsigned char *in, size_t inl, unsigned char *out) /* {{{ */
{

    while (inl > 2) { /* keep going until we have less than 24 bits */
        *out++ = base64_table[in[0] >> 2];
        *out++ = base64_table[((in[0] & 0x03) << 4) + (in[1] >> 4)];
        *out++ = base64_table[((in[1] & 0x0f) << 2) + (in[2] >> 6)];
        *out++ = base64_table[in[2] & 0x3f];

        in += 3;
        inl -= 3; /* we just handle 3 octets of data */
    }

    /* now deal with the tail end of things */
    if (inl != 0) {
        *out++ = base64_table[in[0] >> 2];
        if (inl > 1) {
            *out++ = base64_table[((in[0] & 0x03) << 4) + (in[1] >> 4)];
            *out++ = base64_table[(in[1] & 0x0f) << 2];
            *out++ = base64_pad;
        } else {
            *out++ = base64_table[(in[0] & 0x03) << 4];
            *out++ = base64_pad;
            *out++ = base64_pad;
        }
    }

    *out = '\0';

    return out;
}
/* }}} */

你可能感兴趣的:(PHP 内核源码 base64_encode)