在C ++中打印浮点数的二进制表示 [英] Print binary representation of a float number in C++

查看:581
本文介绍了在C ++中打印浮点数的二进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在C ++中浮动到二进制

在C ++中的浮点数的二进制表示。不太实用,只是出于好奇。

I want to print out the binary representation of a float number in C++. Not very practical, just out of curiosity.

以下程序不编译。 reinterpret_cast失败。我可以使用什么样的演员,以便我可以做&(1<

The following program doesn't compile though. The reinterpret_cast fails. What kind of cast can I use so that I can do the " &(1 << i) " part?

#include <iostream>
using namespace std;


void toBinary(float num) {
  int numi = reinterpret_cast<int>(num);
  cout << num << " " << numi << endl;
  for (int i = 0; i < 8 * sizeof(num); i++){
    if (numi & (1<<i)) {
      cout << 1;
    } else {
      cout << 0;
    }
  }
  cout << endl << endl;
}

int main() {
  float a;
  cout << sizeof(int) << " " << sizeof(float) << endl;
  a = 13.5;
  toBinary(a);
  toBinary(13.9);
  toBinary(2 * a);
  toBinary(-a);
}


推荐答案

取指向浮点的指针,并将其重新指向char的指针。现在循环通过sizeof(float)并将每个字符转换为8个二进制数字。此方法也适用于双打。

There's a much easier way. Take a pointer to the float, and reinterpret_cast it to a pointer to char. Now loop through sizeof(float) and convert each char to 8 binary digits. This method works for doubles too.

这篇关于在C ++中打印浮点数的二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆