Kingkong Jnr Kingkong Jnr - 4 months ago 33
C Question

C typecasting uint32 to uint16

typedef struct a{
uint32 val1;

typedef struct b{
uint16 copy_val1;

void function1(A input)
B my_input;

my_input.copy_val1 = (uint16) input.val1; <-- Is this clean?

Inititally when struct a was designed, it was thought that val1 will contain two 16 bit values. However we chose to use only one 16 bit.

Now I am changing the copy_val1's type from uint32 to uint16 to save memory.
How should I typecast in a clean way and make sure that the 16 bit value from val1 get's copied to copy_val1?

The OS is vxworks in MIPS architecture.


Simply assigning the uint32 value to a uint16 variable, without a cast, is sufficient.

However, you run the risk of truncation. You should consider checking to see if val1 > UINT16_MAX before assignment.

Also note that for structures larger than one or two machine registers, you should pass pointers to structures. Otherwise you incurr a potentially large copy. Do note the change in semantics, however.