DUDS
Distributed Update of Data from Something
SignedMagnitudeToTwosComplement.hpp
Go to the documentation of this file.
1 #include <type_traits>
2 
3 namespace duds { namespace general {
4 
23 template <unsigned B, typename T>
24 inline typename std::make_signed<T>::type SignedMagnitudeToTwosComplement(
25  const T x
26 ) {
27  // one sign bit and one magnitude bit is the minimum requirement for this
28  // operation to make sense
29  static_assert(
30  B > 1,
31  "At least 2 bits are required for signed magnitude input."
32  );
33  // the sign bit must be inside the integer type
34  static_assert(
35  B <= (sizeof(T) * 8),
36  "The signed magnitude input must fit within the integer type."
37  );
38  struct {
39  typename std::make_signed<T>::type x:B;
40  } s;
41  s.x = (typename std::make_signed<T>::type)x;
42  if (s.x < 0) {
43  s.x = (~(1 << (B - 1)) & s.x) * -1;
44  }
45  return s.x;
46 }
47 
48 } }
std::make_signed< T >::type SignedMagnitudeToTwosComplement(const T x)
Converts a signed magnitude value to two&#39;s complement.