Advertisement
Guest User

twos_compl_abs

a guest
Jun 14th, 2017
444
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.35 KB | None | 0 0
  1. // Custom abs(), that correctly handles most-negative values on 2's complement systems.
  2. // Requires T to be either unsigned, or convertible to unsigned.
  3.  
  4. #include <type_traits>
  5.  
  6. template<typename T, typename R = std::make_unsigned_t<T>>
  7. R twos_compl_abs(T val) {
  8.     if (val >= 0) { return val; }
  9.     else          { return static_cast<R>(val) * -1; }
  10. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement