Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - unsigned int to unsigned char array conversion

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.

like image 954
Jake Avatar asked Apr 25 '12 16:04

Jake


2 Answers

How about:

ch[0] = num & 0xFF;
ch[1] = (num >> 8) & 0xFF;

The converse operation is left as an exercise.

like image 36
cnicutar Avatar answered Oct 30 '22 16:10

cnicutar


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.

like image 104
jpalecek Avatar answered Oct 30 '22 16:10

jpalecek