您的位置:首页 > 其它

介绍一种将ASCII码字符串转换为二进制字节数据的方法

2009-02-26 11:43 751 查看
/**     
* @brief 该函数实现了将可打印ASCII码字符串转换为二进制字节数据  
* @param[in] pSrc 源数据指针 
* @param[out] pDst 目标字符串指针 
* @param[in] nSrcLength 源数据长度 
* @param[out] nDstLength 目标字符串长度
* @return 返回操作结果
* - 0 表示操作成功
* - -1 表示操作失败

* @author wlq_729@163.com   
*      http://blog.csdn.net/rabbit729  
* @version 1.0    
* @date 2009-02-26  
*/ 

#include <ctype.h>
#include <iostream>
using namespace std;

int hex2bin(const char* pSrc, unsigned char* pDst, unsigned int nSrcLength, unsigned int& nDstLength)
{
	if ( (pSrc == 0) || (pDst == 0) )
	{
		return -1;
	}

	nDstLength = 0;

	if ( pSrc[0] == 0 ) // nothing to convert
		return 0;

	// 计算需要转换的字节数
	for ( int j = 0; pSrc[j]; j++ )
	{
		if ( isxdigit(pSrc[j]) )
			nDstLength++;
	}

	// 判断待转换字节数是否为奇数,然后加一
	if ( nDstLength & 0x01 ) nDstLength++;
	nDstLength /= 2;

	if ( nDstLength > nSrcLength )
		return -1;

	nDstLength = 0;

	int phase = 0;

	for ( int i = 0; pSrc[i]; i++ )
	{
		if ( ! isxdigit(pSrc[i]) )
			continue;

		unsigned char val = pSrc[i] - ( isdigit(pSrc[i]) ? 0x30 : ( isupper(pSrc[i]) ? 0x37 : 0x57 ) );

		if ( phase == 0 )
		{
			pDst[nDstLength] = val << 4;
			phase++;
		}
		else
		{
			pDst[nDstLength] |= val;
			phase = 0;
			nDstLength++;
		}
	}

	return 0;
}

void main(void)
{
	char test[] = "23a4B7";
	unsigned char result[4];
	memset(result, 0, 4);

	unsigned int nResult = 0; 
	hex2bin(test, result, 6, nResult);
	cout<<result<<endl;
	cout<<nResult<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: