C ++-const char转换为十六进制字节const char [关闭]

问题描述 投票:0回答:1
我在C ++中有此字符串:

const char str1[] = "24 00 15 25 00 00 D2";

我需要将其转换为字符串:

const char str2[] = "\x24\x00\x15\x25\x00\x00\xD2";

最快最简单的转换方法是什么?

编辑:在第二个字符串中,我不需要字符,但需要BYTES。这就是为什么我有一个接受输入str2并执行字节模式扫描的功能的原因。现在可以使用以下字符串:PatterScan(“ \ x24 \ x00 \ x15 \ x25 \ x00 \ x00 \ xD2”);

但是为了给我做更快的事情,我先担心在const char字符串中写入字节,然后将它们转换(str1到str2)。

c++ char hex byte const
1个回答
0
投票
要填充给定的char缓冲区,请使用此:

#include <iostream> #include <string> #include <cstring> void convert(const char* in, size_t count_out, char* out) { size_t count_in = strlen(in); size_t o = 0; if(o >= count_out - 2) return; // error output buffer to small out[o++] = '\\'; out[o++] = 'x'; out[o] = 0; for(size_t i = 0; i < count_in; ++i) { if(in[i]!=' ') { if(o >= count_out - 1) return; // error output buffer to small out[o++] = in[i]; out[o] = 0; } else { if(o >= count_out - 2) return; // error output buffer to small out[o++] = '\\'; out[o++] = 'x'; out[o] = 0; } } } int main() { const char str1[] = "24 00 15 25 00 00 D2"; char str2[100]; convert(str1, 100, str2); std::cout << str2; // outputs: \x24\x00\x15\x25\x00\x00\xD2 }

可能更短或更短或更优雅。
© www.soinside.com 2019 - 2024. All rights reserved.