在 c++ 中将字符串转换为字节

Convert string to bytes in c++

本文关键字:转换 字节 字符串 c++      更新时间:2023-10-16

我是 c++ 的新手,仍在努力摸索。我尝试调整我在 SO 上找到的一个函数,以根据需要将我的字符串转换为字节:

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.001n", );

我遇到的问题是:

1(我不确定如何修改for循环来处理我的字符串。 2(我不确定我应该使用什么作为函数中第二个参数的输入。

谁能帮忙?

谢谢

这是我建议的解决方案。我用它来将 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;
}
}

请记住,两个 ascii 字符构成一个字节,因此对于每对字符,我必须将第一个字符转换为字节,然后将其向上移动 4 位,然后与下一个字符一起移动以获得一个字节。

将字符串打印为字节:

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";
}

要记住的一些重要规则:
1. 将字符复制到整数类型变量中,以便cout不会打印为字符。
2. 字节无符号。
3.用0填充宽度表示十六进制时,请记住在打印十进制之前将其重置为空格。
4.使用std::hex以十六进制打印,并记得在之后用std::dec重置它(如果之后以十进制打印(。

请参阅<iomanip>

编辑 1:C 样式 要使用 C 语言样式

static const char data[] = "Hello World!";
const size_t length = strlen(data);
for (size_t i = 0; i < length; ++i)
{
printf("%3d (0x%02X)n", data[i], data[i]);
}

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