将有符号转换为无符号,反之亦然 [英] Converting Signed to Unsigned and vice versa

查看:162
本文介绍了将有符号转换为无符号,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to implement two functions that convert signed to unsigned and vice versa. I am using c++11 and Linux.

系统是二进制补码,可以接受char,int,long等。接口必须如上所述,试图实现的东西。有更好的方法吗?这些是正确的吗?如何根据位数更改实现?我需要一些建议。

The system is two's complement and can take char, int, long etc.. The interface must be as stated and I have tried to implement something. Are there better ways to do this? Are these correct? How can I change the implementation based on the number of bits? I need some advice.

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一起使用。所以,我可能需要将返回类型的值限制为18bits或4等...

I need to specifiy the bits as this will be used with HW. So, I may need to limit the value in the return type to 18bits or 4 etc...

推荐答案

例如: std :: cout<< unsignedToSigned(signedToUnsigned(-13,0),0); // prints 13 NOT -13

static_cast code> std :: cout<< static_cast < int32_t>(static_cast< uint32_t>(-13)); // prints -13

static_cast will survive the round trip: std::cout << static_cast< int32_t >( static_cast< uint32_t >( -13 ) ); // prints -13

所以我认为 static_cast 可以用更清晰的规格更新问题。

So I think static_cast is what you want unless you can update the question with a clearer specification.

这篇关于将有符号转换为无符号,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆