c++ - Actor 签名到更窄的签名

标签 c++ casting

If the destination type is signed, the value does not change if the source integer can be represented in the destination type.

如果我理解得很好,是否可以保证:

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/

相关文章:

c++ - C++中的互联网使用情况监控工具

c++ - 将 void** 转换为 T** 的问题

PHP JSON API - 检测返回值的数据类型

具有父类(super class)引用的 java 转换

c++ - 我怎样才能摆脱 C++ 中的强制转换?

c++ - C++基本内容。什么东西少了???不可能那么明显

C++ 数组,平均值(初级)

c++ - 从 sregex (Boost Xpressive) 中获取原始正则表达式

c++ - 在 C++ 类中嵌入的其他函数中使用 main 函数的结果

java - 为什么我需要施法?