简体   繁体   中英

compile-time conversion char* to bytes

I have a lot of conversion from const string (known in compile time) to byte string. Now I do it using this function:

std::string StrToHex(std::string);
"0f120a" -> {0x0f, 0x12, 0x0a};

But it take a lot of time, I'd like to generate all this string in compile-time.

conversion from const string (known in compile time) to byte string

To demonstrate that the data (of a string) is already a byte string, Consider the following code


#include <iostream>
using std::cout, std::hex, std::dec;

#include <string>
using std::string;

#include <iomanip>
using std::setw;


// s1 does NOT change
const string s1 = "0123456789Ab";

cout << "\n  letters: ";
for (uint i=0; i<s1.size(); ++i)
{
   cout << "  " << setw(4) << s1[i];
}

cout << "\n      hex: " << hex;   // format info
for (uint i=0; i<s1.size(); ++i)
{
   cout << "  " << setw(4) << static_cast<int>(s1[i]);
}  //                      // ^^^^^^^^^^^ use the char as an int 

cout << "\n  decimal: " << dec;
for (uint i=0; i<s1.size(); ++i)
{
   cout << "  " << setw(4) << static_cast<int>(s1[i]);
}  //                      // ^^^^^^^^^^^ use the char as an int

cout << "\n  letters: (confirm s1 did not change)";
for (uint i=0; i<s1.size(); ++i)
{
   cout << "  " << setw(4) << s1[i];
}

Output... the bytes of string can be printed as chars, hex ints, or decimal ints.

  letters:      0     1     2     3     4     5     6     7     8     9     A     b
      hex:     30    31    32    33    34    35    36    37    38    39    41    62
  decimal:     48    49    50    51    52    53    54    55    56    57    65    98
  letters:      0     1     2     3     4     5     6     7     8     9     A     b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM