ITeye博客

111111

byytj · 2012-12-14 01:23 · 编程语言 · Markdown

  1. // t4.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include <string>
  5. #include <iostream>
  6. #include <cctype>
  7. #include <algorithm>
  8. /*
  9. 入口参数:pSrc  源十六进制数据
  10. 出口参数:dest  存放运算结果
  11. 返回:true  转换成功
  12. false 失败
  13. */
  14. bool Hex2String(unsigned char *pSrc,std::string &dest,int nL)
  15. {
  16. char buf[256];
  17. memset((char *)buf,0,sizeof(buf));
  18. unsigned char hb;
  19. unsigned char lb;
  20. for(int i=0;i<nL;i++)
  21. {
  22. hb=(pSrc[i]&0xf0)>>4;
  23. if( hb>=0 && hb<=9 )
  24. hb += 0x30;
  25. else if( hb>=10 &&hb <=15 )
  26. hb = hb -10 + 'A';
  27. else
  28. return false;
  29. lb = pSrc[i]&0x0f;
  30. if( lb>=0 && lb<=9 )
  31. lb += 0x30;
  32. else if( lb>=10 && lb<=15 )
  33. lb = lb - 10 + 'A';
  34. else
  35. return false;
  36. buf[i*2]   = hb;
  37. buf[i*2+1] = lb;
  38. }
  39. dest = buf;
  40. return true;
  41. }
  42. /*
  43. 入口参数:src  源字符串
  44. 出口参数:dest  存放运算结果
  45. 返回:true  转换成功
  46. false 失败
  47. */
  48. bool String2Hex(std::string &src,unsigned char *dest)
  49. {
  50. unsigned char hb;
  51. unsigned char lb;
  52. if(src.size()%2!=0)
  53. return false;
  54. transform(src.begin(), src.end(), src.begin(), toupper);
  55. for(int i=0, j=0;i<src.size();i++)
  56. {
  57. hb=src[i];
  58. if( hb>='A' && hb<='F' )
  59. hb = hb - 'A' + 10;
  60. else if( hb>='0' && hb<='9' )
  61. hb = hb - '0';
  62. else
  63. return false;
  64. i++;
  65. lb=src[i];
  66. if( lb>='A' && lb<='F' )
  67. lb = lb - 'A' + 10;
  68. else if( lb>='0' && lb<='9' )
  69. lb = lb - '0';
  70. else
  71. return false;
  72. dest[j++]=(hb<<4)|(lb);
  73. }
  74. return true;
  75. }
  76. //下面是使用举例,在VisualStudio2008+SP1中调试通过
  77. int _tmain(int argc, _TCHAR* argv[])
  78. {
  79. unsigned char srcB[]={0x12,0x34,0x56,0x78,0x90,0xab,0xbc,0xcd,0xde,0xef};
  80. std::string strDest;
  81. Hex2String(srcB,strDest,sizeof(srcB));
  82. std::cout<<"HexToString:"<<strDest<<std::endl;
  83. if(String2Hex(strDest,srcB))
  84. std::cout<<"StringToHex:Success!"<<std::endl;
  85. else
  86. std::cout<<"StringToHex:Failed!"<<std::endl;
  87. return 0;
  88. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。