C++ Pass bytes from char* to a BYTE*

  • A+
Category:Languages

I would like to know how to pass/COPY a sequence of bytes represented as a char* to a BYTE* in C++ in Windows.

Let's say I have this char* :

const char *ByteString = "/x3B/xC8/x74/x1B"   

How would I COPY each byte from this char* to a BYTE *Bytes and vice-versa ?

EDIT: Thanks alot for everyone's help !

 


The definition of BYTE is:

typedef unsigned char BYTE;

which is not the same as a const char, so you'd need to convert it, but note that casting away const from something declared const to start with results in undefined behaviour and trying to actually change the data poses an even bigger risk.

BYTE* Bytes = reinterpret_cast<BYTE*>(const_cast<char*>(ByteString));

Edit: I just noticed that converting a const char* to a BYTE* was taken out of the question but I'll leave it here for now.


Copying the data (not as a zero terminated string) could be done like this:

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 

Or better:

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. 

But given the nature of what you are doing, you could probably skip these conversions and use an array of the correct type to start with:

BYTE Bytes[] = { 0xA1, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xC8, 0x74, 0x1B }; 

or

std::basic_string<BYTE> Bytes({ 0xA1, 0x00, 0x00, 0x00, 0x00, 0x3B, 0xC8, 0x74, 0x1B }); 

These won't need any conversions when all you deal with is raw BYTE data. Here's an example using ReadProcessMemory and a basic_string for a buffer and pattern.

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: