我想知道如何在 Windows 的 C++ 中将表示为 char*
的字节序列传递/复制到 BYTE*
。
假设我有这个 char*
:
const char *ByteString = "\x3B\xC8\x74\x1B"
我如何将此 char* 中的每个字节复制到 BYTE *Bytes
中,反之亦然?
编辑:非常感谢大家的帮助!
最佳答案
BYTE
的定义是:
typedef unsigned char BYTE;
这与 const char
不同,因此您需要对其进行转换,但请注意丢弃 const
来自声明的东西 const
从导致未定义行为的结果开始并尝试实际更改数据会带来更大的风险。
BYTE* Bytes = reinterpret_cast<BYTE*>(const_cast<char*>(ByteString));
编辑:我刚刚注意到转换 const char*
到 BYTE*
被排除在外,但我暂时将其留在这里。
可以像这样复制数据(不是以零结尾的字符串):
const char ByteString[] = "\x3B\xC8\x74\x1B";
BYTE* Bytes = new BYTE[sizeof(ByteString)-1];
std::memcpy(Bytes, ByteString, sizeof(ByteString)-1);
// Use your Bytes
delete[] Bytes; // manual delete when you are done
或者更好:
const char ByteString[] = "\x3B\xC8\x74\x1B";
std::basic_string<BYTE> Bytes( reinterpret_cast<const BYTE*>(ByteString), sizeof(ByteString)-1 );
// use Bytes
// Bytes.data() returns a BYTE*
// Bytes.size() returns the length.
但是考虑到您正在做的事情的性质,您可能可以跳过这些转换并使用正确类型的数组作为开始:
BYTE Bytes[] = { 0xA1, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xC8, 0x74, 0x1B };
或
std::basic_string<BYTE> Bytes({ 0xA1, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xC8, 0x74, 0x1B });
当您处理的都是原始数据时,这些不需要任何转换 BYTE
数据。这是一个使用 ReadProcessMemory
的示例和一个 basic_string
用于缓冲区和模式。
using BYTEstr = std::basic_string<BYTE>; // just for convenience
BYTEstr Buffer(1024, 0); // 1024 BYTES initialized with 0
BYTEstr Pattern({ 0xA1, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xC8, 0x74, 0x1B });
ReadProcessMemory(hProcess, lpBaseAddress, Buffer.data(), Buffer.size(), &lpNumberOfBytesRead);
BYTEstr::size_type pos = Buffer.find(Pattern);
if (pos == BYTEstr::npos) {
std::cout << "Pattern not found\n";
} else {
std::cout << "Pattern found at position " << pos << "\n";
}
关于C++ 将字节从 char* 传递到 BYTE*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54580584/