uint16_t to unsigned char

キャンセル
次の結果を表示 
表示  限定  | 次の代わりに検索 
もしかして: 

uint16_t to unsigned char

ソリューションへジャンプ
4,712件の閲覧回数
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 解決策
4,456件の閲覧回数
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

元の投稿で解決策を見る

1 返信
4,457件の閲覧回数
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