- // t4.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <string>
- #include <iostream>
- #include <cctype>
- #include <algorithm>
- /*
- 入口参数:pSrc 源十六进制数据
- 出口参数:dest 存放运算结果
- 返回:true 转换成功
- false 失败
- */
- bool Hex2String(unsigned char *pSrc,std::string &dest,int nL)
- {
- char buf[256];
- memset((char *)buf,0,sizeof(buf));
- unsigned char hb;
- unsigned char lb;
- for(int i=0;i<nL;i++)
- {
- hb=(pSrc[i]&0xf0)>>4;
- if( hb>=0 && hb<=9 )
- hb += 0x30;
- else if( hb>=10 &&hb <=15 )
- hb = hb -10 + 'A';
- else
- return false;
- lb = pSrc[i]&0x0f;
- if( lb>=0 && lb<=9 )
- lb += 0x30;
- else if( lb>=10 && lb<=15 )
- lb = lb - 10 + 'A';
- else
- return false;
- buf[i*2] = hb;
- buf[i*2+1] = lb;
- }
- dest = buf;
- return true;
- }
- /*
- 入口参数:src 源字符串
- 出口参数:dest 存放运算结果
- 返回:true 转换成功
- false 失败
- */
- bool String2Hex(std::string &src,unsigned char *dest)
- {
- unsigned char hb;
- unsigned char lb;
- if(src.size()%2!=0)
- return false;
- transform(src.begin(), src.end(), src.begin(), toupper);
- for(int i=0, j=0;i<src.size();i++)
- {
- hb=src[i];
- if( hb>='A' && hb<='F' )
- hb = hb - 'A' + 10;
- else if( hb>='0' && hb<='9' )
- hb = hb - '0';
- else
- return false;
- i++;
- lb=src[i];
- if( lb>='A' && lb<='F' )
- lb = lb - 'A' + 10;
- else if( lb>='0' && lb<='9' )
- lb = lb - '0';
- else
- return false;
- dest[j++]=(hb<<4)|(lb);
- }
- return true;
- }
- //下面是使用举例,在VisualStudio2008+SP1中调试通过
- int _tmain(int argc, _TCHAR* argv[])
- {
- unsigned char srcB[]={0x12,0x34,0x56,0x78,0x90,0xab,0xbc,0xcd,0xde,0xef};
- std::string strDest;
- Hex2String(srcB,strDest,sizeof(srcB));
- std::cout<<"HexToString:"<<strDest<<std::endl;
- if(String2Hex(strDest,srcB))
- std::cout<<"StringToHex:Success!"<<std::endl;
- else
- std::cout<<"StringToHex:Failed!"<<std::endl;
- return 0;
- }
111111
最新推荐文章于 2019-10-31 21:47:16 发布