MIME之Quoted-Printable編解碼

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

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

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;
}

發佈了0 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章