简体   繁体   中英

Endianness on reinterpret_cast

I have a pointer to an uint8_t aray. Each 2 elements are actually a uint_16_t value and I want to use reinterpret_cast :

uint16_t *Dst16Rgb = reinterpret_cast<uint16_t*>(Dst8Rgb);

The output has the wrong endianness, is there a way to specify reinterpret_cast if I want to do it on little or big endian?

Thanks!

I have a pointer to an uint8_t aray. Each 2 elements are actually a uint_16_t

Either you actually have an array of uint8_t , or you actually have an array of uint_16_t . It cannot be both.

 uint16_t *Dst16Rgb = reinterpret_cast<uint16_t*>(Dst8Rgb);

Indirecting through the reinterpret pointer will have undefined behaviour since there is no uint16_t object at the pointed address.

Even if you disable strict aliasing, there is still UB unless you guarantee that the byte array is sufficiently aligned for uint_16_t .

is there a way to specify reinterpret_cast if I want to do it on little or big endian?

No. Data is always reintepreted in native endianness. If the input bytes have different endianness, then the result will be "wrong".

You must know the endianness of the input data. You can read bytes as a multi-byte integer without knowing the native endianness by shifting and masking.

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