简体   繁体   中英

Endian-safe conversion from uint16 with value less than 256 to uint8

I am interacting with an API that returns uint16_t values; in this case I know that the value is never going to exceed 255. I need to convert the value to a uint8_t for usage with a separate API. I am currently doing this in the following way:

uint16_t u16_value = 100;
uint8_t u8_value = u16_value << 8;

This solution currently exposes endianness issues if moving from a little-endian (my current system) to a big-endian system.

What is the best way to mitigate against this?

From cppreference

For unsigned and positive a, the value of a << b is the value of a * 2**b , reduced modulo maximum value of the return type plus 1 (that is, bitwise left shift is performed and the bits that get shifted out of the destination type are discarded).

There's nothing about endianness here. You can just do

uint16_t u16_value = 100;
uint8_t u8_value = u16_value;

or

uint16_t u16_value = 100;
uint8_t u8_value = static_cast<uint8_t>(u16_value);

To be explicit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM