编译时将字符*转换为字节

compile-time conversion char* to bytes

本文关键字:转换 字节 字符 编译      更新时间:2023-10-16

我有很多从常量字符串(在编译时已知(到字节字符串的转换。 现在我使用这个函数来做:

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

但这需要很多时间,我想在编译时生成所有这些字符串。

从常量字符串(在编译时已知(到字节字符串的转换

为了证明(字符串的(数据已经是一个字节字符串, 请考虑以下代码


#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];
}

输出。。。字符串的字节可以打印为字符、十六进制整数或十进制整数。

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