c++实现Quoted-Printable编码

1.源码实现

#include 
#include 
#include 

unsigned char hex_2_char(const char *u)
{
    unsigned char a, b, c;

    if(u[0] >= 'a' && u[0] <= 'z')
    {
        a = u[0] - 'a' + 10;
    }
    else if(u[0] >= 'A' && u[0] <= 'Z')
    {
        a = u[0] - 'A' + 10;
    }
    else if(u[0] >= '0' && u[0] <= '9')
    {
        a = u[0] - '0';
    }

    if(u[1] >= 'a' && u[1] <= 'z')
    {
        b = u[1] - 'a' + 10;
    }
    else if(u[1] >= 'A' && u[1] <= 'Z')
    {
        b = u[1] - 'A' + 10;
    }
    else if(u[1] >= '0' && u[1] <= '9')
    {
        b = u[1] - '0';
    }

    return ((a << 4) | b);
}

void char_2_hex(const unsigned char u, char *v, char flag)
{
    unsigned char a, b;
    char start = flag ? 'a' : 'A';

    a = u >> 4;
    b = (u & 15);

    if(a >= 0 && a <= 9)
    {
        v[0] = a + '0';
    }
    else
    {
        v[0] = a - 10 + start;
    }

    if(b >= 0 && b <= 9)
    {
        v[1] = b + '0';
    }
    else
    {
        v[1] = b - 10 + start;
    }
}

int encode_quoted(const unsigned char *src, char *dst, int length, int max)
{       
    int len[2];
    int i;

    len[0] = 0;
    len[1] = 0;
        
    for(i=0; i= '!') && (*src <= '~') && (*src != '='))
        {
            *dst++ = *src;
            len[0]++;
            len[1]++;
        }
        else
        {
            dst[0] = '=';
            char_2_hex(*src, dst+1, 0);

            dst += 3;
            len[0] += 3;
            len[1] += 3;
        }
                
        if(len[1] >= max - 3)
        {
            dst[0] = '=';
            dst[1] = '\r';
            dst[2] = '\n';

            dst += 3;
            len[0] += 3;
            len[1] = 0;
        }
    }
        
    *dst = 0x00;
        
    return len[0];
}

int decode_quoted(const char *src, unsigned char *dst, int length)
{
    int len;
    int i;
 
    i = 0;
    len = 0;
 
    while(i < length)
    {
        if(strncmp(src, "=\r\n", 3) == 0)
        {
            src += 3;
            i += 3;
        }
        else
        {
            if(*src == '=')
            {
                dst[0] = hex_2_char(src+1);
                dst++;
                src += 3;
                i += 3;
            }
            else
            {
                *dst++ = (unsigned char)*src++;
                i++;
            }
  
            len++;
        }
    }
 
    *dst = 0x00;
 
    return len;
}

int main()
{
    unsigned char src[1024] = "你好,世界";
    char dst[1024];
    char tmp[1024];
    int len = strlen(src);

    tmp[0] = 0x00;

    encode_quoted(src, dst, len, 36);

    len = strlen(dst);

    decode_quoted(dst, tmp, len);

    printf("%s\n", dst);
    printf("%s\n", tmp);

    return 0;
}

2.编译源码

$ gcc -o test test.c -std=c89

3.运行及其结果

$ ./test
=E4=BD=A0=E5=A5=BD=EF=BC=8C=E4=B8=
=96=E7=95=8C
你好,世界

你可能感兴趣的:(c++实现Quoted-Printable编码)