---
title: "111111"
author: "byytj"
date: "2012-12-14T01:23:42Z"
tags: []
categories: ["编程语言"]
slug: "111111"
draft: false
lastmod: "2012-12-14T01:23:42Z"
id: 1747508
url: "https://byytj.iteye.com/blog/1747508"
---

01. // t4.cpp : Defines the entry point for the console application.
02. //
03. #include "stdafx.h"
04. #include &lt;string&gt;
05. #include &lt;iostream&gt;
06. #include &lt;cctype&gt;
07. #include &lt;algorithm&gt;
08. /*
09. 入口参数：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&lt;nL;i++)
21. {
22. hb=(pSrc\[i]&0xf0)&gt;&gt;4;
23. if( hb&gt;=0 && hb&lt;=9 )
24. hb += 0x30;
25. else if( hb&gt;=10 &&hb &lt;=15 )
26. hb = hb -10 + 'A';
27. else
28. return false;
29. lb = pSrc\[i]&0x0f;
30. if( lb&gt;=0 && lb&lt;=9 )
31. lb += 0x30;
32. else if( lb&gt;=10 && lb&lt;=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&lt;src.size();i++)
56. {
57. hb=src\[i];
58. if( hb&gt;='A' && hb&lt;='F' )
59. hb = hb - 'A' + 10;
60. else if( hb&gt;='0' && hb&lt;='9' )
61. hb = hb - '0';
62. else
63. return false;
64. i++;
65. lb=src\[i];
66. if( lb&gt;='A' && lb&lt;='F' )
67. lb = lb - 'A' + 10;
68. else if( lb&gt;='0' && lb&lt;='9' )
69. lb = lb - '0';
70. else
71. return false;
72. dest\[j++]=(hb&lt;&lt;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&lt;&lt;"HexToString:"&lt;&lt;strDest&lt;&lt;std::endl;
83. if(String2Hex(strDest,srcB))
84. std::cout&lt;&lt;"StringToHex:Success!"&lt;&lt;std::endl;
85. else
86. std::cout&lt;&lt;"StringToHex:Failed!"&lt;&lt;std::endl;
87. return 0;
88. }