fork download
  1. #include <bitset>
  2. #include <cmath>
  3. #include <iostream>
  4.  
  5. const int kExponentBits = 11;
  6. const int kSignificandBits = 52;
  7.  
  8. std::bitset<kExponentBits + kSignificandBits + 1> FloatToBinaryIEEE754(double x) {
  9. if (x == 0) {
  10. return 0;
  11. } else if (std::isinf(x)) {
  12. return (1ull << kExponentBits + kSignificandBits) |
  13. ((x < 0) << (kExponentBits + kSignificandBits));
  14. } else if (std::isnan(x)) {
  15. return (1ull << kExponentBits + kSignificandBits) |
  16. (1ull << (kExponentBits - 1)) | 1;
  17. }
  18.  
  19. int exponent;
  20. double significand = frexp(x, &exponent);
  21. exponent += (1 << (kExponentBits - 1)) - 1;
  22.  
  23. std::bitset<kExponentBits + kSignificandBits + 1> result;
  24. result = (unsigned long long)(significand * (1ull << kSignificandBits)) &
  25. ((1ull << kSignificandBits) - 1);
  26. result |= (unsigned long long)(exponent) << kSignificandBits;
  27. result |= (x < 0) << (kExponentBits + kSignificandBits);
  28. return result;
  29. }
  30.  
  31. int main() {
  32. double x = 0.25;
  33. std::bitset<kExponentBits + kSignificandBits + 1> binary = FloatToBinaryIEEE754(x);
  34. std::cout << binary << std::endl;
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0.01s 5504KB
stdin
Standard input is empty
stdout
0011111111101000000000000000000000000000000000000000000000000000