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...
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?
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
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.