C – unsigned int to unsigned char array conversion

bytec++type-conversionunsigned-charunsigned-integer

I have an unsigned int number (2 byte) and I want to convert it to unsigned char type. From my search, I find that most people recommend to do the following:

 unsigned int x;
 ...
 unsigned char ch = (unsigned char)x;

Is the right approach? I ask because unsigned char is 1 byte and we casted from 2 byte data to 1 byte.

To prevent any data loss, I want to create an array of unsigned char[] and save the individual bytes into the array. I am stuck at the following:

 unsigned char ch[2];
 unsigned int num = 272;

 for(i=0; i<2; i++){
      // how should the individual bytes from num be saved in ch[0] and ch[1] ??
 }

Also, how would we convert the unsigned char[2] back to unsigned int.

Thanks a lot.

Best Solution

You can use memcpy in that case:

memcpy(ch, (char*)&num, 2); /* although sizeof(int) would be better */

Also, how would be convert the unsigned char[2] back to unsigned int.

The same way, just reverse the arguments of memcpy.