[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppDoubleToBitString

(C++) Convert a double to a std::string of bits

The code below should not use union but a reinterpret_cast.

  1. include <iostream>
  2. include <string>
  3. include <cassert>
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; }


last edited (November 15, 2006) by bilderbikkel, Number of views: 2236, Current Rev: 3 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.