Are you using a VC10? There is already a problem: Microsoft connect. I would also suggest that you can fix this by exposing the int type if it is 32 bits, for example:
string s = ToBinary(*reinterpret_cast<int*>(&buffer_u[1]));
This can be done inside the method, if necessary. However, the result of reinterpretation should no longer be used for arithmetic .;)
Works well as a workaround for me (but looks pretty ugly)
template<typename T> std::string ToBinary(const T& value) { switch (sizeof(T)) { case 8: return std::bitset<std::numeric_limits<T>::digits + 1>(*reinterpret_cast<const long*>(&value)).to_string(); case 4: return std::bitset<std::numeric_limits<T>::digits + 1>(*reinterpret_cast<const int*>(&value)).to_string(); case 2: return std::bitset<std::numeric_limits<T>::digits + 1>(*reinterpret_cast<const short*>(&value)).to_string(); case 1: return std::bitset<std::numeric_limits<T>::digits + 1>(*reinterpret_cast<const char*>(&value)).to_string(); } return "n/a"; }
source share