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