#include <iostream>
using namespace std;
int gsmEncode7bit(const char* pSrc, unsigned char* pDst, int nSrcLength);
int gsmDecode7bit(const unsigned char* pSrc, char* pDst, int nSrcLength);
int main()
{
const char* ypSrc = "1";
unsigned char* ypDst;
int ynSrcLength = sizeof ypSrc;
gsmEncode7bit(ypSrc,ypDst,ynSrcLength+1);
system("pause");
}
// 7bit編碼
// 輸入: pSrc - 源字符串指針
// nSrcLength - 源字符串長度
// 輸出: pDst - 目標(biāo)編碼串指針
// 返回: 目標(biāo)編碼串長度
int gsmEncode7bit(const char* pSrc, unsigned char* pDst, int nSrcLength)
{
int nSrc; // 源字符串的計數(shù)值
int nDst; // 目標(biāo)編碼串的計數(shù)值
int nChar; // 當(dāng)前正在處理的組內(nèi)字符字節(jié)的序號,范圍是0-7
unsigned char nLeft; // 上一字節(jié)殘余的數(shù)據(jù)
// 計數(shù)值初始化
nSrc = 0;
nDst = 0;
// 將源串每8個字節(jié)分為一組,壓縮成7個字節(jié)
// 循環(huán)該處理過程,直至源串被處理完
// 如果分組不到8字節(jié),也能正確處理
while (nSrc < nSrcLength)
{
// 取源字符串的計數(shù)值的最低3位
nChar = nSrc & 7;
// 處理源串的每個字節(jié)
if(nChar == 0)
{
// 組內(nèi)第一個字節(jié),只是保存起來,待處理下一個字節(jié)時使用
nLeft = *pSrc;
}
else
{
// 組內(nèi)其它字節(jié),將其右邊部分與殘余數(shù)據(jù)相加,得到一個目標(biāo)編碼字節(jié)
*pDst = (*pSrc << (8-nChar)) | nLeft;
// 將該字節(jié)剩下的左邊部分,作為殘余數(shù)據(jù)保存起來
nLeft = *pSrc >> nChar;
// 修改目標(biāo)串的指針和計數(shù)值
pDst++;
nDst++;
}
// 修改源串的指針和計數(shù)值
pSrc++;
nSrc++;
}
// 返回目標(biāo)串長度
return nDst;
}
// 7bit解碼
// 輸入: pSrc - 源編碼串指針
// nSrcLength - 源編碼串長度
// 輸出: pDst - 目標(biāo)字符串指針
// 返回: 目標(biāo)字符串長度
int gsmDecode7bit(const unsigned char* pSrc, char* pDst, int nSrcLength)
{
int nSrc; // 源字符串的計數(shù)值
int nDst; // 目標(biāo)解碼串的計數(shù)值
int nByte; // 當(dāng)前正在處理的組內(nèi)字節(jié)的序號,范圍是0-6
unsigned char nLeft; // 上一字節(jié)殘余的數(shù)據(jù)
// 計數(shù)值初始化
nSrc = 0;
nDst = 0;
// 組內(nèi)字節(jié)序號和殘余數(shù)據(jù)初始化
nByte = 0;
nLeft = 0;
// 將源數(shù)據(jù)每7個字節(jié)分為一組,解壓縮成8個字節(jié)
// 循環(huán)該處理過程,直至源數(shù)據(jù)被處理完
// 如果分組不到7字節(jié),也能正確處理
while(nSrc<nSrcLength)
{
// 將源字節(jié)右邊部分與殘余數(shù)據(jù)相加,去掉最高位,得到一個目標(biāo)解碼字節(jié)
*pDst = ((*pSrc << nByte) | nLeft) & 0x7f;
// 將該字節(jié)剩下的左邊部分,作為殘余數(shù)據(jù)保存起來
nLeft = *pSrc >> (7-nByte);
// 修改目標(biāo)串的指針和計數(shù)值
pDst++;
nDst++;
// 修改字節(jié)計數(shù)值
nByte++;
// 到了一組的最后一個字節(jié)
if(nByte == 7)
{
// 額外得到一個目標(biāo)解碼字節(jié)
*pDst = nLeft;
// 修改目標(biāo)串的指針和計數(shù)值
pDst++;
nDst++;
// 組內(nèi)字節(jié)序號和殘余數(shù)據(jù)初始化
nByte = 0;
nLeft = 0;
}
// 修改源串的指針和計數(shù)值
pSrc++;
nSrc++;
}
// 輸出字符串加個結(jié)束符
*pDst = '\0';
// 返回目標(biāo)串長度
return nDst;
}
posted on 2010-11-25 10:49
jemmyLiu 閱讀(744)
評論(0) 編輯 收藏 引用 所屬分類:
C++BASE