Possible Duplicate:
Best way to detect integer overflow in C/C++
What is the best way to detect if integer truncation occurred?
Edit
This should cause truncation being signalled but it doesn't
#include <iostream>
using std::cout;
typedef signed int int32_t;
typedef unsigned int uint32_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;
int32_t my32bitInt = 0xffffffff;
int32_t tmp = my32bitInt & 0xFFFF8000;
uint16_t ss = my32bitInt;
int main()
{
if (tmp != 0xFFFF8000 && tmp != 0x00000000)
{ // cannot be converted safely
cout << "truncation";
}
cout << ss << '\n';
cout << my32bitInt << '\n';
return 0;
}
Edit 2
template <typename U, typename T>
bool is_safe(T t)
{
return sizeof(U) <= sizeof(T) ?
(t >= static_cast<T>(std::numeric_limits<U>::min()))
&& (t <= static_cast<T>(std::numeric_limits<U>::max())) : true;
}
Edit 3 (Based on Oli's <>) - I found some problems, but working on it, will update asap
template bool is_safe(Source value) {
if (sizeof(Result) == sizeof(Source))
{/*Same size*/
if (std::is_same<Source,Result>::value)
{
//signed to signed or unsigned to unsigned when size is same - no problem
return true;
}
else
{
//MSB mustn't be set in Source
return !(value & (1u << ((sizeof(Source) * CHAR_BIT) - 1)));
}
}
else
{//smaller to larger and larger to smaller
if (sizeof(Result) <= sizeof(Source))
{ //Larger to smaller and both equal
return ((value >= static_cast<Source>(std::numeric_limits<Result>::min()))
&& (value <= static_cast<Source>(std::numeric_limits<Result>::max())));
}
else
{ //smaller to larger
if (std::is_signed<Source>::value && !std::is_signed<Result>::value)
{
//signed to unsigned - signed must be positive
return (value >= 0);
}
else
{
return true;
}
}
}
}