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