Question

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.

Was it helpful?

Solution 2

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.)

OTHER TIPS

union u
{
    unsigned char dataArray[8];
    U32 sysTime[2];
}

u s;
s.sysTime[0]=2400;
s.sysTime[0]=1200;

And you were wrong. What you are trying to do is to fit 4 byte integer to 1 byte dataArray[0]. This assignment will convert your int value to char by truncating 3 bytes on MSB side.
What you actually were trying (probably) to do is:

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

This will copy all 4 bytes from sysTime to first four bytes in dataArray.
This way you will have access to any byte of your sysTime value, but won't be able to read your integer back by calling dataArray[0], since it will give you only 1 byte of original value).

If you want to read your value back you have to convert address of char to address of U32:

*((U32*)(&dataArray[0]))

what step by step does:

  1. dataArray[0] -> first element of dataArray>
  2. &dataArray[0] -> get address of first element of dataArray (char* - pointer to 1 byte)
  3. (U32 *)(&dataArray[0]) -> convert char* to U32 * (pointer to 1 byte becomes pointer to 4 bytes)
  4. *(U32 *)(&dataArray[0]) -> dereference result of above (Read four bytes from given address)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top