Low and High DWORD => size_t

3k Views Asked by At

Programming language: C

I have two DWORDs: A low and a high one. I want to convert them both into one variable of type size_t. I have the following code:

size_t fileSize = fileSizeHigh;
size_t *pfileSize = &fileSize;
pfileSize[4] = fileSizeLow;

is it right that way? I guess not since the first command probably stores the high-byte in the wrong position, right? Please help me on how to do this. Thank You :)

2

There are 2 best solutions below

0
On

So, on a 32-bit Microsoft system, a DWORD is the same size as a size_t. This means that you cannot fit two DWORDs into the space occupied by a size_t.

Your code will simply write into memory beyond the end of fileSize and has undefined behaviour. It will not do what you want.

What is it you're actually trying to accomplish? What is the task you are trying to complete? Tell us that and we may be able to offer you an alternate solution.

Edit: As @nos explains, on a 64-bit system a size_t can hold two DWORDs. If you're using a 64-bit system, you can use bit shifting to combine the two:

size_t combined = ((size_t)high << 32) | (size_t)low; // 64-BIT WINDOWS ONLY

However, this is still a bit of a code smell, because operations on 64-bit Windows targets are meant to be very similar to those on 32-bit targets, so it still looks like you're doing something for an odd reason.

3
On

If you're writing 64 bit code, a size_t is normally 64 bit. You need to verify this on your platform. A DWORD is usually 32 bit, you need to verify that too. Given 32 bit DWORD and 64 bit size_t, you do this:

DWORD a = ...;
DWORD b = ...;
size_t c = (size_t)a << 32 | b;

If you're writing 32 bit code, it would not make sense to combine 2 32 bit types into another 32 bit type, size_t is normally 32 bit in 32 bit code.