Read a DWORD from a BYTE array

Jul 2, 2015 at 2:48am
I have used ReadFile to fill a BYTE buffer. How can I access the first 4 bytes of it as a DWORD?
 
LPBYTE readBuffer = new BYTE[1024];


I tried some things like this:
 
if ((DWORD)&readBuffer[0] == NULL) ......
Jul 2, 2015 at 4:33am
*(DWORD *)readBuffer
Jul 2, 2015 at 5:47am
The basic idea is to treat the buffer as a pointer to DWORD, and dereference it.

However if you read it from a file, it could be a different story. If the file was created on a different type of machine, it could save the bytes in a different order.

It I recall correctly, in most PC, we store a DWORD (for example 0x12345678) like this:

78 56 34 12

But in some machines, it was saved like

12 34 56 78
Jul 2, 2015 at 11:17pm
Nice, that works. But I need to write a dword and then a zero-terminated string to the buffer.

The DWORD is easy, the same as reading from it but how do I write a Zstring right after it? (I am using interprocess communication so I'm reading and writing to a byte buffer, if you're curious)

I tried this
1
2
*(DWORD *)writeBuffer = RESPONSECODE;
*(char *)writeBuffer+4 = "This is a test...";
Jul 2, 2015 at 11:29pm
Use memcpy() or strcpy().
Jul 4, 2015 at 11:27pm
Thanks, I got it running on the first try with:
 
strcpy ((char *)writeBuffer+4,"copy successful");
Jul 4, 2015 at 11:54pm
Just make sure the destination is always large enough to contain the source.
Jul 5, 2015 at 12:53am
Crap, I figured out that I should have used:
 
*(DWORD *)(writeBuffer+4)

to actually read/write 4 bytes after the start of the buffer. Heh.
Last edited on Jul 5, 2015 at 12:53am
Topic archived. No new replies allowed.