在C ++中从24位到32位的带符号扩展 [英] Signed extension from 24 bit to 32 bit in C++
本文介绍了在C ++中从24位到32位的带符号扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个无符号字节分别通过网络传输.
I have 3 unsigned bytes that are coming over the wire separately.
[byte1, byte2, byte3]
我需要将它们转换为带符号的32位值,但我不太确定如何处理负值的符号.
I need to convert these to a signed 32-bit value but I am not quite sure how to handle the sign of the negative values.
我考虑过将字节复制到int32的高3个字节中,然后将所有内容向右移动,但我读到这可能会发生意外的行为.
I thought of copying the bytes to the upper 3 bytes in the int32 and then shifting everything to the right but I read this may have unexpected behavior.
有没有更简单的方法来解决这个问题?
Is there an easier way to handle this?
该表示法使用二进制补码.
The representation is using two's complement.
推荐答案
您可以使用:
uint32_t sign_extend_24_32(uint32_t x) {
const int bits = 24;
uint32_t m = 1u << (bits - 1);
return (x ^ m) - m;
}
之所以有效,是因为:
- 如果旧符号为1,则XOR将其设置为零,减法将对其进行设置,并借用所有较高的位,并将它们也进行设置.
- 如果旧符号为0,则XOR将对其进行设置,减法将其重新设置并且不借位,因此高位保持为0.
模板版本
template<class T>
T sign_extend(T x, const int bits) {
T m = 1;
m <<= bits - 1;
return (x ^ m) - m;
}
这篇关于在C ++中从24位到32位的带符号扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文