# uint16_t to unsigned char

cancel
Showing results for
Show  only  | Search instead for
Did you mean:
SOLVED

## uint16_t to unsigned char

3,786 Views
Contributor IV

Hello, I tried to convert uint16_t to unsigned char. Make some search on internet and find some methods but didnt understand and not sure code will work.

typedef struct {
unsigned char *datax;
unsigned int size;
unsigned char *datay;
}message;

main code:

uint16_t x,y;

/* x and y get values by another function and ı am trying to do convert.*/

msg->datax = ((unsigned char *)(&x));
msg->datay = ((unsigned char *)(&y));

Is the transform okey ? Is there any other way?

Tags (4)
1 Solution
3,530 Views
Senior Contributor V

In your example, you are not converting anything: all what you do is to cast a pointer from (uint16_t*) to (uint8_t*).

So if you read from your casted pointer, you simply will read from the MSB.

if you want to read the lower 8bits of a 16bit, you simply can do someting like

uint8_t val8u;

uint16_val16u = 0x1234;

val8u = val16u; // implicit cast, val8u will be assigned with 0x34;

If you want the upper bits:

val8u = (val16u>>8); // shift and implicit cast, val8u will have value 0x12

I hope this helps,

Erich

3,531 Views
Senior Contributor V

In your example, you are not converting anything: all what you do is to cast a pointer from (uint16_t*) to (uint8_t*).

So if you read from your casted pointer, you simply will read from the MSB.

if you want to read the lower 8bits of a 16bit, you simply can do someting like

uint8_t val8u;

uint16_val16u = 0x1234;

val8u = val16u; // implicit cast, val8u will be assigned with 0x34;

If you want the upper bits:

val8u = (val16u>>8); // shift and implicit cast, val8u will have value 0x12

I hope this helps,

Erich