[英]Portable conversion from unsigned to signed in C++
I have std::vector<unsigned short int> vals
for which I need to invert the order of the bytes (assume 2) and store them as short int
.我有
std::vector<unsigned short int> vals
,我需要反转字节的顺序(假设为 2)并将它们存储为short int
。 I was doing it as:我这样做是:
std::vector<short int> result;
for(unsigned short int& x : vals) {
x = ((x << 8) | (x >> 8));
result.push_back(static_cast<short int>(x));
}
Reading online, I find that static_cast
has implementation-defined behavior.在线阅读,我发现
static_cast
具有实现定义的行为。 I also found std::bit_cast
, which preserves the bits and interprets them in the new type.我还找到了
std::bit_cast
,它保留了这些位并以新类型解释它们。
Does that mean that using std::bit_cast<short int>(x)
above should be preferred over static_cast
?这是否意味着使用上面的
std::bit_cast<short int>(x)
应该优于static_cast
?
I tried, and both give the same results for me.我试过了,两者都给了我相同的结果。 Is it correct to assume that
bit_cast
will give the same results to anyone else using my code, while static_cast
could give them different results?假设
bit_cast
会给使用我的代码的其他人提供相同的结果,而static_cast
可以给他们不同的结果是否正确?
If you want to handle bytes - you should not convert them to a non byte type (especially not short int
and friends because they does not need to be 16 bits exactly).如果您想处理字节 - 您不应该将它们转换为非字节类型(尤其不是
short int
和朋友,因为它们不需要完全是 16 位)。 You should read the bytes as an array of char
or std::byte
.您应该将字节读取为
char
或std::byte
数组。 Then you can swap those values in safe and portable manner.然后,您可以以安全且可移植的方式交换这些值。 Converting those bytes to a numeric type is not doable in portable way.
以可移植的方式将这些字节转换为数字类型是不可行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.