Duraisamy
Duraisamy

Reputation: 27

How to assign uint16_t value into uint8_t array?

I have the following data

uint16_t a[1] = { 0x2321 };

I want to convert to uint8_t as:

uint8_t b[1] = { 0x21 };

How can I do it in a C program?

Upvotes: 1

Views: 9662

Answers (3)

M.M
M.M

Reputation: 141554

Just

b[0] = a[0];

or in a declaration inside a function (this is not legal at file scope):

uint8_t b[1] = { a[0] };

There is a well-defined implicit conversion from unsigned intgral types to smaller unsigned integral types; the value is reduced modulo (1 + maximum value of the smaller type).

You don't need any casts or bitmask operations, although some compilers may give a specious (IMHO) warning about loss of precision if you don't write a cast to suppress this warning.

Upvotes: 1

Bart Friederichs
Bart Friederichs

Reputation: 33511

Use a bitmask to get the least significant byte:

uint8_t b[1];
b[0] = (a[0] & 0xff);

Upvotes: 2

Eric Fournie
Eric Fournie

Reputation: 1372

Cast the lower byte:

uint16_t a[1] = {0x2321};
uint8_t b[1] = {(uint8_t)(a[0] & 0xFF)};

Upvotes: 6

Related Questions