otsdaq  v2_04_01
BinaryStringMacros.cc
1 #include "otsdaq-core/Macros/BinaryStringMacros.h"
2 
3 using namespace ots;
4 
5 //========================================================================================================================
6 // binaryToHexString
7 // convert a data buffer of <len> bytes to a hex string 2*len characters long
8 // Note: no preamble is applied by default (but "0x" could be nice)
9 //
10 // Note: this is used with defaults by VisualSupervisor
11 std::string BinaryStringMacros::binaryToHexString(const char* binaryBuffer,
12  unsigned int numberOfBytes,
13  const std::string& resultPreamble,
14  const std::string& resultDelimiter)
15 {
16  std::string dest;
17  dest.reserve(numberOfBytes * 2);
18  char hexstr[3];
19 
20  for(unsigned int i = 0; i < numberOfBytes; ++i)
21  {
22  sprintf(hexstr, "%02X", (unsigned char)binaryBuffer[i]);
23  if(i)
24  dest += resultDelimiter;
25  dest += hexstr;
26  }
27  return resultPreamble + dest;
28 } // end binaryToHexString
29 
30 //========================================================================================================================
31 // binaryTo8ByteHexString
32 // convert a data buffer string a hex string
33 // 8 bytes at a time with the least significant byte last.
34 // Note: no preamble is applied by default (but "0x" could be nice)
35 std::string BinaryStringMacros::binaryTo8ByteHexString(const std::string& binaryBuffer,
36  const std::string& resultPreamble,
37  const std::string& resultDelimiter)
38 {
39  std::string dest;
40  dest.reserve(binaryBuffer.size() * 2 +
41  resultDelimiter.size() * (binaryBuffer.size() / 8) +
42  resultPreamble.size());
43  char hexstr[3];
44 
45  dest += resultPreamble;
46 
47  unsigned int j = 0;
48  for(; j + 8 < binaryBuffer.size(); j += 8)
49  {
50  if(j)
51  dest += resultDelimiter;
52  for(unsigned int k = 0; k < 8; ++k)
53  {
54  sprintf(hexstr, "%02X", (unsigned char)binaryBuffer[7 - k + j * 8]);
55  dest += hexstr;
56  }
57  }
58  for(unsigned int k = binaryBuffer.size() - 1; k >= j; --k)
59  {
60  sprintf(hexstr, "%02X", (unsigned char)binaryBuffer[k]);
61  dest += hexstr;
62  if(k == 0)
63  break; // to handle unsigned numbers when j is 0
64  }
65 
66  return dest;
67 } // end binaryTo8ByteHexString