1 // Copyright (c)
2 // All rights reserved.
3 //
4 //Describe : Hex string
5 //Author : Qing
6 //Date : 2014-08-14
7
8 #ifndef __HEX_STRING_H__
9 #define __HEX_STRING_H__
10
11 #include <string>
12
13 namespace Qing
14 {
15 class HexString
16 {
17 public:
18
19 HexString(void);
20 ~HexString(void);
21
22 int HexCharToInt(char ch) const;
23 std::string AddSpace(const std::string &SourcesString, int Interval) const;
24
25 void HexToString(const unsigned char* HexCharArray, int ArraySize, unsigned char* TargetBuffer, int BufferSize) const;
26 void StringToHex(std::string &MyString, const unsigned char* SourcesCharArray, int ArraySize, bool IsLowerCase) const;
27 };
28 }
29
30 #endif
1 #include "StdAfx.h"
2 #include "HexString.h"
3
4 namespace Qing
5 {
6 HexString::HexString(void)
7 {
8 }
9
10 HexString::~HexString(void)
11 {
12 }
13
14 int HexString::HexCharToInt(char Ch) const
15 {
16 if(Ch >= '0' && Ch <= '9') return (Ch - '0');
17 if(Ch >= 'A' && Ch <= 'F') return (Ch - 'A' + 10);
18 if(Ch >= 'a' && Ch <= 'f') return (Ch - 'a' + 10);
19
20 return 0;
21 }
22
23 std::string HexString::AddSpace(const std::string &SourcesString, int Interval) const
24 {
25 std::string Space(" ");
26 std::string TempString = SourcesString;
27
28 for(std::string::size_type Index = Interval; Index < TempString.size(); Index += Interval)
29 {
30 TempString.insert(Index, Space);
31 ++Index;
32 }
33
34 return TempString;
35 }
36
37 void HexString::HexToString(const unsigned char* HexCharArray, int ArraySize, unsigned char* TargetBuffer, int BufferSize) const
38 {
39 memset(TargetBuffer, 0, BufferSize);
40
41 for(int Index = 0; Index < ArraySize; Index+=2)
42 {
43 TargetBuffer[Index/2] = static_cast<char>(((HexCharToInt(HexCharArray[Index]) << 4) | HexCharToInt(HexCharArray[Index+1])));
44 }
45 }
46
47 void HexString::StringToHex(std::string &MyString, const unsigned char* SourcesCharArray, int ArraySize, bool IsLowerCase) const
48 {
49 MyString.clear();
50 std::string FlagString(IsLowerCase ? "0123456789abcdef" : "0123456789ABCDEF");
51
52 int b = 0;
53 for(int i = 0; i < ArraySize; i++)
54 {
55 b = 0x0f & (SourcesCharArray[i] >> 4);
56 MyString.append(1, FlagString.at(b));
57
58 b = 0x0f & SourcesCharArray[i];
59 MyString.append(1, FlagString.at(b));
60 }
61 }
62 }