如果我理解得很好,是否可以保证:
static_cast<std::int8_t>(static_cast<std::int16_t>(-3)) == -3
?
因为 -3 可以用 std::int8_t 表示。
因此在两个 s 补码的例子中:
然后在two's complement function的例子中,我需要一个中间转换为 std::uintmax_t 吗?
#include <type_traits>
template <typename T>
T twos_complement(T val)
{
typedef std::make_unsigned<T>::type U;
return static_cast<T>(-static_cast<uintmax_t>(static_cast<U>(val)));
}
因为
return static_cast<T>(-static_cast<U>(val));
如果 T 比 int 窄,在一元减号之前应用整数提升会“破坏转换为无符号类型的效果”吗?
最佳答案
你为什么不像这样得到补码:
uint32_t num = 10;
uint32_t cmp = ~num + 1; // this is two's complement of 10.
这不适合你吗?
编辑:如果您担心可能会发生溢出(无论是签名还是未签名),请先执行此操作:
if(~num == std::numeric_limits<MyIntType>::max()) {
// overflow mitigation
}
您还可以使用 std::is_signed
以适当的方式静态检查您的类型是有符号的还是无符号的,以减轻溢出问题。和 std::is_unsigned
.
关于c++ - Actor 签名到更窄的签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53496737/