简体   繁体   English

从值小于256的uint16到uint8的字节序安全转换

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

I am interacting with an API that returns uint16_t values; 我正在与一个返回uint16_t值的API进行交互; 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. 在这种情况下,我知道该值永远不会超过255。我需要将该值转换为uint8_t以便与单独的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 来自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). 对于无符号且为正数的a, a << b的值是a * 2**b值,即返回类型的模极大值加1(即,按位向左移位并且移出的位类型的目标将被丢弃)。

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. 明确地说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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