www.pudn.com > SendMsgOCX.rar > ByteHexStrConvert.cpp


#include "stdafx.h" 
 
#include  
#include  
#include  
 
//作用:将  pBytes处,长度为nBytes的字节,转换为十六进制数字(字母大写),存于str 
//说明:调用程序必须保证  str的长度为    2*nBytes + 1(NULL) 
//返回:转换后的字节数,不包括加入的NULL,实际  ==  2*nBytes  
//作者:wangwwcn99@cn99.com 
//最后修改:00-4-19 12:39:56 
int ByteToHexStr(const unsigned char*pBytes, int nBytes, char* str) 
{ 
	if( nBytes <= 0 ) return 0; 
 
	int len = 0; 
	int temp; 
	while(nBytes--) 
	{ 
		temp = *pBytes++; 
		len += sprintf(str, "%02X", temp ); 
		str++; str++; 
	} 
 
	return len; 
} 
 
//作用:将十六进制数字串str,转换为BYTE,存于pBytes 
//说明:调用程序必须保证pBytes 的长度, str的长度应该是偶数    
//返回:转换后的字节数,实际  ==  str长度  / 2 
//作者:wangwwcn99@cn99.com 
//最后修改:00-4-19 12:39:56 
 
int HexStrToByte(const char*str, unsigned char*pBytes) 
{ 
	_ASSERT( strlen( str ) % 2 == 0 ); 
 
	int len = 0; 
	int temp; 
	while(*str) 
	{ 
		//采用2x格式时,sscanf会自动根据数据长度往后写4个字节!!,而不是1个字节 
		sscanf(str, "%2X", &temp );	*pBytes++ = temp; 
		 
		len++; 
		str++; str++; 
	} 
	return len; 
} 
 
//作用:将十六进制数字串str,的前len字节  转换为BYTE,存于pBytes 
//说明:调用程序必须保证pBytes 的长度, len应该是偶数    
//返回:转换得到的字节数,实际就是len/2 
//作者:wangwwcn99@cn99.com 
//最后修改: 2000年5月27日11:49:29 
 
 
int HexStrLenToByte(const char*str, int len, unsigned char*pBytes) 
{ 
	_ASSERT( len % 2 == 0 );   //must be an even number 
	 
	int temp; int nReturn = len/2; 
	while( len ) 
	{	 
		//采用2x格式时,sscanf会自动根据数据长度往后写4个字节!!,而不是1个字节 
		sscanf(str, "%2X", &temp ); *pBytes++ = temp; 
		len--; len--; 
		str++; str++; 
	} 
	 
	return nReturn; 
}