码迷,mamicode.com
首页 > 编程语言 > 详细

C 语言实现 php base64_encode

时间:2016-09-21 09:05:46      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

这是在网上找到的一段代码,因为需求不同,稍微做了下修改,有需要的朋友可以直接复制使用。

unsigned char *base64_encode(const unsigned char *str, size_t length)
{
    if (NULL == str || 0 == length)
        return NULL;

    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 = =;
    const unsigned char *current = str;
    //int length = strlen(str);
    unsigned char *p;
    unsigned char *result;

    if ((length + 2) < 0 || ((length + 2) / 3) >= (1 << (sizeof(int) * 8 - 2))) 
    {
        return NULL;
    }

    result = (unsigned char *)malloc(((length + 2) / 3) * 4 * sizeof(char) + 1);
    p = result;

    while (length > 2)
    { 
        *p++ = base64_table[current[0] >> 2];
        *p++ = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)];
        *p++ = base64_table[((current[1] & 0x0f) << 2) + (current[2] >> 6)];
        *p++ = base64_table[current[2] & 0x3f];

        current += 3;
        length -= 3; 
    }

    if (length != 0)
    {
        *p++ = base64_table[current[0] >> 2];
        if (length > 1)
        {
            *p++ = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)];
            *p++ = base64_table[(current[1] & 0x0f) << 2];
            *p++ = base64_pad;
        }
        else
        {
            *p++ = base64_table[(current[0] & 0x03) << 4];
            *p++ = base64_pad;
            *p++ = base64_pad;
        }
    }
    *p = \0;
    return result;
}

 

C 语言实现 php base64_encode

标签:

原文地址:http://www.cnblogs.com/john-h/p/5891344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!