Home | Mirror | SearchITEYE 博客 | OSChina 博客 | 51CTO 博客

Chapter 6. Quoted-Printable

Table of Contents

6.1. C Quoted-Printable
6.2. Java Quoted-Printable
6.3. Python Quoted-Printable

Quoted-Printable也是MIME郵件中常用的編碼方式之一。同Base64一樣,它也將輸入的字元串或數據編碼成全是ASCII碼的可打印字元串。

Quoted-Printable編碼的基本方法是:輸入數據在33-60、62-126範圍內的,直接輸出;其它的需編碼為“=”加兩個位元組的HEX碼(大寫)。為保證輸出行不超過規定長度,可在行尾加“=\r\n”序列作為軟回車。

6.1. C Quoted-Printable

		
int EncodeQuoted(const unsigned char* pSrc, char* pDst, int nSrcLen, int nMaxLineLen)
{
    int nDstLen;        // 輸出的字元計數
    int nLineLen;       // 輸出的行長度計數
 
    nDstLen = 0;
    nLineLen = 0;
 
    for (int i = 0; i < nSrcLen; i++, pSrc++)
    {
        // ASCII 33-60, 62-126原樣輸出,其餘的需編碼
        if ((*pSrc >= '!') && (*pSrc <= '~') && (*pSrc != '='))
        {
            *pDst++ = (char)*pSrc;
            nDstLen++;
            nLineLen++;
        }
        else
        {
            sprintf(pDst, "=%02X", *pSrc);
            pDst += 3;
            nDstLen += 3;
            nLineLen += 3;
        }
 
        // 輸出換行?
        if (nLineLen >= nMaxLineLen - 3)
        {
            sprintf(pDst, "=\r\n");
            pDst += 3;
            nDstLen += 3;
            nLineLen = 0;
        }
    }
 
    // 輸出加個結束符
    *pDst = '\0';
 
    return nDstLen;
}
		
		

Quoted-Printable解碼很簡單,將編碼過程反過來就行了。

		
int DecodeQuoted(const char* pSrc, unsigned char* pDst, int nSrcLen)
{
    int nDstLen;        // 輸出的字元計數
    int i;
 
    i = 0;
    nDstLen = 0;
 
    while (i < nSrcLen)
    {
        if (strncmp(pSrc, "=\r\n", 3) == 0)        // 軟回車,跳過
        {
            pSrc += 3;
            i += 3;
        }
        else
        {
            if (*pSrc == '=')        // 是編碼位元組
            {
                sscanf(pSrc, "=%02X", pDst);
                pDst++;
                pSrc += 3;
                i += 3;
            }
            else        // 非編碼位元組
            {
                *pDst++ = (unsigned char)*pSrc++;
                i++;
            }
  
            nDstLen++;
        }
    }
 
    // 輸出加個結束符
    *pDst = '\0';
 
    return nDstLen;
}
		
		

參考:http://dev.csdn.net/develop/article/19/19205.shtm

comments powered by Disqus