Problems with storing unsigned entries in a char array in C

advertisements

I am having a problem with storing unsigned ints in a character array in C. The code i have is

static unsigned char dataArray[8];

// values before are 2400 and 2100
// array layout: 0 0 0 0 0 0 0 0

U32 sysTime1 = 2400;
U32 sysTime2 = 2100;

dataArray[0] = sysTime1;
dataArray[4] = sysTime2;

// values after are 96 and 52
// array layout: 96 0 0 0 52 0 0 0

How do i get the correct values to be stored in the array? I thought that if you stored a four byte data type in a char array from index 0, it would take up room from index 0 to 3 and so on. Any help would be much appreciated. The U32 is an unsigned 32 bit (4 byte) integer.


Your assignments truncates the values, as you only assign the lowest byte of them.

You need to do something like this

*((U32 *) &dataArray[0]) = sysTime1;
*((U32 *) &dataArray[4]) = sysTime2;

Or use e.g. memcpy:

memcpy(&dataArray[0], &sysTime1, sizeof(sysTime1));
memcpy(&dataArray[4], &sysTime2, sizeof(sysTime2));

And you can of course get and assign each byte of the value:

dataArray[0] = (sysTime1 >> 24) & 0xff;
dataArray[1] = (sysTime1 >> 16) & 0xff;
dataArray[2] = (sysTime1 >>  8) & 0xff;
dataArray[3] =  sysTime1        & 0xff;

(And the same for the other.)