将字符串转换为c+中的字节+; 我是C++新手,仍然在摸索着前进。我已尝试调整在上找到的函数,以便根据需要将字符串转换为字节: void hexconvert(const char *text, unsigned char bytes[]) { int i; int temp; for (i = 0; i < 4; ++i) { sscanf(text + 2 * i, "%2x", &temp); bytes[i] = temp; } cout << bytes; } hexconvert("SKY 000.001\n", ); void hexconvert(常量字符*文本,无符号字符字节[]) { int i; 内部温度; 对于(i=0;i

将字符串转换为c+中的字节+; 我是C++新手,仍然在摸索着前进。我已尝试调整在上找到的函数,以便根据需要将字符串转换为字节: void hexconvert(const char *text, unsigned char bytes[]) { int i; int temp; for (i = 0; i < 4; ++i) { sscanf(text + 2 * i, "%2x", &temp); bytes[i] = temp; } cout << bytes; } hexconvert("SKY 000.001\n", ); void hexconvert(常量字符*文本,无符号字符字节[]) { int i; 内部温度; 对于(i=0;i,c++,string,byte,C++,String,Byte,将字符串打印为字节: const size_t length = data.length(); for (size_t i = 0; i < length; ++i) { unsigned int value = data[i]; std::cout << std::dec << std::fill(' ') << value << " (0x" << std::setw(2) << s

将字符串打印为字节:

const size_t length = data.length();
for (size_t i = 0; i < length; ++i)
{
  unsigned int value = data[i];
  std::cout << std::dec << std::fill(' ') << value
            << " (0x" << std::setw(2) << std::setfill('0') << std::hex << value << ')'
            << "\n";
}

上面假设
数据
是一个字符数组,以nul结尾。

这是我建议的解决方案。我使用它将GUID编码为字节数组。它应该比必须对所有字符执行
printf
更高的性能

typedef unsigned char byte;

std::map<char, byte> char2hex = 
{
  {'0', 0x0},
  {'1', 0x1},
  {'2', 0x2},
  {'3', 0x3},
  {'4', 0x4},
  {'5', 0x5},
  {'6', 0x6},
  {'7', 0x7},
  {'8', 0x8},
  {'9', 0x9},
  {'a', 0xa},
  {'b', 0xb},
  {'c', 0xc},
  {'d', 0xd},
  {'e', 0xe},
  {'f', 0xf}
};

void convertToBytes(const string &chars, byte bytes[])
{
  for (size_t i = 0; i < chars.length() / 2; i++) {
    byte b1 = (byte)(char2hex[chars[2*i]] << 4);
    byte b2 = char2hex[chars[2*i+1]];
    byte f = b1 | b2;
    *(bytes + i) = f;
  }
}
typedef无符号字符字节;
std::map char2hex=
{
{'0',0x0},
{'1',0x1},
{'2',0x2},
{'3',0x3},
{'4',0x4},
{'5',0x5},
{'6',0x6},
{'7',0x7},
{'8',0x8},
{'9',0x9},
{'a',0xa},
{'b',0xb},
{'c',0xc},
{'d',0xd},
{'e',0xe},
{'f',0xf}
};
void convertToBytes(常量字符串和字符,字节[])
{
对于(大小i=0;ibyte b1=(byte)(char2hex[chars[2*i]]为什么不直接执行
std::cout hi,感谢您的回复。如果我需要访问我的变量以进行控制台打印以外的操作,这将如何工作?
typedef unsigned char byte;

std::map<char, byte> char2hex = 
{
  {'0', 0x0},
  {'1', 0x1},
  {'2', 0x2},
  {'3', 0x3},
  {'4', 0x4},
  {'5', 0x5},
  {'6', 0x6},
  {'7', 0x7},
  {'8', 0x8},
  {'9', 0x9},
  {'a', 0xa},
  {'b', 0xb},
  {'c', 0xc},
  {'d', 0xd},
  {'e', 0xe},
  {'f', 0xf}
};

void convertToBytes(const string &chars, byte bytes[])
{
  for (size_t i = 0; i < chars.length() / 2; i++) {
    byte b1 = (byte)(char2hex[chars[2*i]] << 4);
    byte b2 = char2hex[chars[2*i+1]];
    byte f = b1 | b2;
    *(bytes + i) = f;
  }
}