uint16_t to unsigned char

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

uint16_t to unsigned char

Jump to solution
4,759 Views
omerkaanbasakin
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. 

header code:

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? 

0 Kudos
Reply
1 Solution
4,503 Views
ErichStyger
Specialist I

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

View solution in original post

1 Reply
4,504 Views
ErichStyger
Specialist I

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