0
votes

I don't know how to convert an array of unsigned int to an array of unsigned char in a good way. I would like to receive some suggestions.

To be more clear, my problem is that I have a function that read memory putting data in unsigned int array. I want to get this data and convert to unsigned char to put in, for example, serial port.

Thanks

1
That's rather vague. What are you trying to achieve?Nik Bougalis
What do you really want to do? If you want to reinterpret the bytes, a simple cast is enough. If you want to keep the values (supposing all of them are in the range [0; 255]), you will have to write a loop and copy everything to a new array.marcus

1 Answers

0
votes

You could either use the uint array element by element

for (i=0 ; i<arrayLength ; i++) processuChar((unsigned char) uintarray[i]);

or you could create a new array and copy the elements

unsigned int uintarray[N];
unsigned char uchararray[N];

for (i=0 ; i<N ; i++) uchararray[i] = (unsigned char)uintarray[i];

and then utilize that new uchararray array.

Or it you prefer to dynamically allocate the new array, before the copy

unsigned char *uchararray = malloc(sizeof(unsigned char) * N);
for (i=0 ; i<N ; i++) uchararray[i] = (unsigned char)uintarray[i];

In this case (dynamic) you'll have to free the array when you don't need it anymore

free (uchararray);