C: 4 elements of an array to a DWORD

2.1k views Asked by At

Now can I copy 4 bytes (known start position, NOT 0) in an array (char*data) to a DWORD?

There are two parts to this: first, getting the 4 bytes from the array at the specified position (4 elements, each element is a char which is 1 byte in C), and then moving them to a DWORD.

I'm not sure how to do either.

Thanks!

3

There are 3 answers

8
vmario On BEST ANSWER

You can use memcpy (it requires string.h header):

#include <stdio.h>
#include <string.h>
#include <inttypes.h>

int main(void)
{
    uint8_t array[] = {
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09
    }
    uint32_t dword;
    size_t offset = 2;

    memcpy(&dword, array + offset, sizeof(dword));
    printf("Dword value = 0x%08x\n", dword);

    return 0;
 }
0
glglgl On

What you look for is deserialization. In this case, somewhere must be specified if the data in your char * are big endian (start with the highest byte) or little endian (start with the lowest byte). For portable applications, BE might be the favourite.

After you have done so, your function might look like

uintmax_t readarrayvalue_be(const char * data, uint8_t bytes)
{
    uintmax_t value = 0;
    while (bytes) {
        value <<= 8;
        value |= *(data++) & 0xFF;
        bytes--;
    }
    return value;
}

while in the concrete case it might be restructured as

uint32_t readarrayvalue_u32_be(const char * data)
{
    uint32_t value = ((data[0] & 0xFF) << 24) | ((data[1] & 0xFF) << 16) | ((data[2] & 0xFF) << 8) | (data[3] & 0xFF);
    return value;
}
0
Digital_Reality On

I think below code shoudl work

memcpy(destination, input+offset, howMany);