c++ - 将有符号转换为无符号,反之亦然

标签 c++ linux unsigned

我必须实现两个函数,将有符号转换为无符号,反之亦然。我正在使用 C++11 和 Linux。

该系统是二进制补码,可以采用 char、int、long 等。接口(interface)必须与声明的一样,我已尝试实现一些东西。有更好的方法吗?这些正确吗?如何根据位数更改实现?我需要一些建议。

uint32_t signedToUnsigned(int32_t x, uint8_t bits)
{
    return ( x > 0 ? x:-x);
}

int32_t unsignedToSigned(uint32_t x, uint8_t bits)
{
    if(x <= INT_MAX )
        return static_cast<int>(x);

    if(x >= INT_MIN)
        return static_cast<int>(x - INT_MIN)+ INT_MIN;
    else
    {
        printf("ERROR");
        return x;
    }
}

编辑:

我需要指定位,因为这将与 HW 一起使用。因此,我可能需要将返回类型中的值限制为 18 位或 4 位等...

最佳答案

不是没有位的依赖而是重载函数:

uint32_t signedToUnsigned(int32_t x);
uint64_t signedToUnsigned(int64_t x);
uint16_t signedToUnsigned(int16_t x);

等等。 但是,简单的 static_cast 应该可以,请阅读:How does one safely static_cast between unsigned int and int?

关于c++ - 将有符号转换为无符号,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26036504/

相关文章:

C++11 static_assert 和模板实例化

c++ - 测试 istream 对象

c - 进程上下文和定时器函数之间的同步

c - 无符号字符数组的输出

java - Java中的无符号短

c# - Mono C# 应用程序使用 boost 组件实例化 C++ 库类

linux - 为 debian 重新编译一个包

linux - 为什么 CLOCKS_PER_SECOND 总是设置为 100 万?

c++ - 'comparison between signed and unsigned integer expressions' 真的会导致错误吗?

c++ - 迭代 std::map 如何返回基于键值的排序元素