Unsigned short to char array

Hi!
I'm trying to assign bits of an unsigned short number to char .
Suppose that we have 2 unsigned short numbers ;

1
2
unsigned short num1 = 30 ;
unsigned short num2 = 740 ;


and a char array
 
char str[4];

What i want it to set bits of str as bits of num1 and num2.

For instance ,
Here , numbers are 16 bits and str is 32 bits.

So what i want is ,
to assign bits of num1 to first 16 bits of str and
to assign bits of num2 to following 16 bits of str.

How can i do it ?

Thanks in advance,
The solution actually depends on the byte ordering of the machine architecture. Assuming that the byte ordering is little endian, and that the size of unsigned short is 2 bytes, the following code does what you want:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>

int main()
{
    union package
    {
        struct Nums
        {
            unsigned short num1;
            unsigned short num2;
        }nums;
        
        char str1[4];
    };
    
    union package p;
    
    p.nums.num1 = 30u; 
    p.nums.num2 = 740u;
    
    char str[4];
    str[0] = p.str1[1];
    str[1] = p.str1[0];
    str[2] = p.str1[3];
    str[3] = p.str1[2];

    // If the architecture is big endian, p.str1 would contain the required values;
    // so you wouldn't need a separate array and the above 4 assignments in that case.
    
    for(int i=0; i<4; i++)
        printf("%d ", str[i]);

    printf("\n");
    return 0;
}


With the assumptions mentioned above, the output of the program would be:

0 30 2 -28

To know more about little endian and big endian, please see http://en.wikipedia.org/wiki/Endianness
If you want a generic method, better convert the numbers into bit strings and make the assignments appropriately.
Topic archived. No new replies allowed.