7Bit压缩解压算法

来源:互联网 发布:php项目用什么软件开发 编辑:程序博客网 时间:2024/06/05 09:09

// 7bit.cpp : 定义控制台应用程序的入口点。

//

 

#include "stdafx.h"

#include <string.h>

#include <stdlib.h>

 

 

unsigned char GetBit(unsigned char uByte, int iBitIndex);

void SetBit(unsigned char* lpByte, int iBitIndex, unsigned char uVal);

int gsmEncode7bit(const char* pSrc, unsigned char* pDst, int nSrcLength);

int gsmDecode7bit(const unsigned char* pSrc, char* pDst, int nSrcLength);

 

int _tmain(int argc, _TCHAR* argv[])

{

char* pSrc = "helloworld";

 

char szDst[100] = {0};

char szSrc[100] = {0};

 

int len = gsmEncode7bit(pSrc, (unsigned char*)szDst, strlen(pSrc));

gsmDecode7bit((unsigned char*)szDst, (char*)szSrc, len);

return 0;

}

 

 

// 7bit编码    

// 输入: pSrc - 源字符串指针    

//       nSrcLength - 源字符串长度    

// 输出: pDst - 目标编码串指针    

// 返回: 目标编码串长度 

int gsmEncode7bit(const char* pSrc, unsigned char* pDst, int nSrcLength) 

{

int iDst;

int nBitsInByte;

unsigned char* szDst = new unsigned char[nSrcLength+1];

memset(szDst, 0x00, nSrcLength+1);

 

iDst = 0;

nBitsInByte = 0;

for (int iSrc = 0; iSrc < nSrcLength; iSrc++)

{

for (int i = 0; i < 7; i++)

{

unsigned char uBitVal = GetBit(*(pSrc+iSrc), i+1);

SetBit(szDst+iDst, nBitsInByte, uBitVal);

nBitsInByte++;

if (nBitsInByte >= 8)

{

nBitsInByte = 0;

iDst++;

}

}

}

 

if (nBitsInByte > 0)

{

iDst++;

}

 

for (int i = 0; i < iDst; i++)

{

sprintf((char*)pDst+2*i, "%02x", *(szDst+i));

}

delete szDst;

szDst = 0;

 

return iDst*2;

}

 

// 7bit解码    

// 输入: pSrc - 源编码串指针    

//       nSrcLength - 源编码串长度    

// 输出: pDst - 目标字符串指针    

// 返回: 目标字符串长度 

int gsmDecode7bit(const unsigned char* pSrc, char* pDst, int nSrcLength)

{

unsigned char uVal;

int iDst = 0;

int nBitsInByte = 1;

 

for (int iSrc = 0; iSrc < nSrcLength; iSrc += 2)

{

sscanf((char*)pSrc+iSrc, "%02x", &uVal);

for (int i = 0; i < 8; i++)

{

unsigned char uBitVal = GetBit(uVal, i);

SetBit((unsigned char*)pDst+iDst, nBitsInByte, uBitVal);

nBitsInByte++;

if (nBitsInByte >= 8)

{

nBitsInByte = 1;

iDst++;

}

}

}

 

if (nBitsInByte > 0)

{

iDst++;

}

 

return iDst;

}

 

unsigned char GetBit(unsigned char uByte, int iBitIndex)

{

unsigned char uVal;

uVal = uByte;

uVal = uVal & (0x80 >> iBitIndex);

uVal = uVal >> (7 - iBitIndex);

return uVal;

}

 

void SetBit(unsigned char* lpByte, int iBitIndex, unsigned char uVal)

{

unsigned char uBit = uVal;

uBit = uBit & 0x01;

*lpByte = *lpByte | (uBit << (7 - iBitIndex));

}

原创粉丝点击