zoukankan      html  css  js  c++  java
  • 用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;
    }
  • 相关阅读:
    S3:代理模式 Proxy
    S2:外观模式 Facade
    S1:适配器 Adapter
    C5:单例模式 Singleton
    C4:原型模式 Prototype
    C3:建造者模式 Builder
    C2:抽象工厂 Abstract Factory
    C1:工厂模式 Factory
    设计模式分类
    数据访问对象模式
  • 原文地址:https://www.cnblogs.com/qq378829867/p/2945665.html
Copyright © 2011-2022 走看看