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;
}
/* }}} */
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 陈氏太极拳老架一路讲义 前言 写给喜爱太极拳的武术朋友们 中华武术,源远流长,今虽门派繁多,实一脉相承。太极拳以它...
    阿德乐阅读 11,164评论 0 12
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,459评论 0 4
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 9,947评论 0 5
  • 《裕语言》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 10...
    叶染柒丶阅读 28,406评论 5 19
  • 张爱玲说爱一个人你会低到尘埃里,可是不会有人爱尘埃里的你 大家都在说八月是分手季,十月是复合季,分开了八个月之后,...
    有趣_9586阅读 1,092评论 0 1