• 用C语言实现PHP的base64_encode函数


    最近写的程序要用到base64_encode,网上一搜“C语言 base64”出来一堆代码,但是我向来是不惮以最坏的恶意来推测这些代码的。于是看了一下PHP源码,base64_encode函数定义在ext\standard\base64.c文件中。我把它改写了一下,需要注意内存是动态分配的,使用完之后记得free掉,否则会造成内存泄露。

    unsigned char *base64_encode(const unsigned char *str)
    {
        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;
    }
  • 相关阅读:
    pymysql 防止sql注入案例
    4、【常见算法】一道经典的额递归题目
    3、【常见算法】寻找非递减序列中绝对值最小值的绝对值
    2、【常见算法】按序重排问题
    9、【排序算法】基数排序
    8、【排序算法】桶排序
    7、【排序算法】归并排序
    6、【排序算法】堆排序
    20、【图】Prim(普里姆)算法
    19、【图】Kruskal(克鲁斯卡尔)算法
  • 原文地址:https://www.cnblogs.com/qq378829867/p/2945665.html
Copyright © 2020-2023  润新知