uint16_t to unsigned char

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 
已解决

uint16_t to unsigned char

跳至解决方案
4,075 次查看
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? 

标记 (4)
0 项奖励
1 解答
3,819 次查看
ErichStyger
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

在原帖中查看解决方案

1 回复
3,820 次查看
ErichStyger
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