Converting Signed to Unsigned and vice versa

痞子三分冷 提交于 2019-12-12 02:55:51

问题


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

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;
    }
}

EDIT:

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...


回答1:


Instead of having dependency of no of bits have overloaded functions as:

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

and so on. However, simple static_cast should do, please read: How does one safely static_cast between unsigned int and int?




回答2:


If you want a number to survive a round trip your functions are not good.

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

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

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



来源:https://stackoverflow.com/questions/26036504/converting-signed-to-unsigned-and-vice-versa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!