[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppDoubleToBitString
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppDoubleToBitString
(C++) Convert a double to a std::string of bits
The code below should not use union but a reinterpret_cast.std::string doubleToBitString(const double& anyDouble) { static union MyUnion { unsigned int myInts[2]; double myDouble; } myUnion; myUnion.myDouble = anyDouble; int myInt0 = myUnion.myInts[0]; int myInt1 = myUnion.myInts[1]; std::string myBitString; for (int i = 0; i<32; ++i) { if (myInt0%2==0) myBitString = "0" + myBitString; else myBitString = "1" + myBitString; myInt0>>=1; } for (int i = 0; i<32; ++i) { if (myInt1%2==0) myBitString = "0" + myBitString; else myBitString = "1" + myBitString; myInt1>>=1; } return myBitString; } int main() { const double zero = 0.0; const double minusZero = -0.0; std::cout << doubleToBitString(zero) << std::endl; std::cout << doubleToBitString(minusZero) << std::endl; }
- include <iostream>
- include <string>
- include <cassert>
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
