Question

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.

Was it helpful?

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.

OTHER TIPS

How about:

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

The converse operation is left as an exercise.

How about using a union?

union {
    unsigned int num;
    unsigned char ch[2];
}  theValue;

theValue.num = 272;
printf("The two bytes: %d and %d\n", theValue.ch[0], theValue.ch[1]);

It really depends on your goal: why do you want to convert this to an unsigned char? Depending on the answer to that there are a few different ways to do this:

  • Truncate: This is what was recomended. If you are just trying to squeeze data into a function which requires an unsigned char, simply cast uchar ch = (uchar)x (but, of course, beware of what happens if your int is too big).

  • Specific endian: Use this when your destination requires a specific format. Usually networking code likes everything converted to big endian arrays of chars:

    int n = sizeof x;
    for(int y=0; n-->0; y++)
        ch[y] = (x>>(n*8))&0xff;
    

    will does that.

  • Machine endian. Use this when there is no endianness requirement, and the data will only occur on one machine. The order of the array will change across different architectures. People usually take care of this with unions:

    union {int x; char ch[sizeof (int)];} u;
    u.x = 0xf00
    //use u.ch 
    

    with memcpy:

    uchar ch[sizeof(int)];
    memcpy(&ch, &x, sizeof x);
    

    or with the ever-dangerous simple casting (which is undefined behavior, and crashes on numerous systems):

    char *ch = (unsigned char *)&x;
    

Of course, array of chars large enough to contain a larger value has to be exactly as big as this value itself. So you can simply pretend that this larger value already is an array of chars:

unsigned int x = 12345678;//well, it should be just 1234.
unsigned char* pChars;

pChars = (unsigned char*) &x;

pChars[0];//one byte is here
pChars[1];//another byte here

(Once you understand what's going on, it can be done without any variables, all just casting)

You just need to extract those bytes using bitwise & operator. OxFF is a hexadecimal mask to extract one byte. Please look at various bit operations here - http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-must-know/

An example program is as follows:

#include <stdio.h>

int main()
{
    unsigned int i = 0x1122;
    unsigned char c[2];

    c[0] = i & 0xFF;
    c[1] = (i>>8) & 0xFF;

    printf("c[0] = %x \n", c[0]);
    printf("c[1] = %x \n", c[1]);
    printf("i    = %x \n", i);

    return 0;
}

Output:

$ gcc 1.c 
$ ./a.out 
c[0] = 22 
c[1] = 11 
i    = 1122 
$
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top