在 c++ 中将字符串转换为字节
Convert string to bytes in c++
我是 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 结尾。
相关文章:
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 将字节数组转换为带有字节序问题的指针
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 如何在连接器 C++ 中将原始字节转换为字符串
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 将字节数组转换为多维数组
- C++如何将字符数组转换为字节向量(向量<byte>)
- 如何在C++中将字节向量(std::vector<uint8_t>)转换为不同的uint32_t,uint16_t和uint8_t变量
- 将字符串转换为无符号字符数组/字节数组
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 将以 null 结尾的字节字符串转换为原始字符串文本
- 正在转换结构数据的字节序
- 如何将 CString 转换为字节 [] 数组?
- 一种将 Dart 中的字节数据转换为 C++ 中的无符号字符*的有效方法?
- 使用 ESP8266/8285 将字符串从 Web 服务器转换为字节数组
- 编译时将字符*转换为字节
- 将字节数组转换为对象C++ |C++中的 C# 位转换器
- C++转换字节
- 将整型转换字节中的字节更改为整数
- c++从字符串化字节转换字节数组