C++ 将字节从 char* 传递到 BYTE*

标签 c++ arrays winapi char

我想知道如何在 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/

相关文章:

java - 在Java中提取光标图像

c++ - 当找不到请求的注册表值时,RegGetValue 返回什么?

c++ - 如何测试 std::function<T> 是否可构造为模板参数 T

c++ - 右键单击按钮

arrays - 如何分离重复的数组?

javascript - 将对象数组合并为单个对象数组

c++ - 如何使用 ATL/WTL 制作您自己的类原生(可复制)控件?

c++ - 确定执行循环所需的 CPU 时间

c++ - 如何找出两个 vector 之间的角度是外部角度还是内部角度?

javascript - Reduce() 一个已经被减少的元素的对象