如何显示浮点数或双精度数的二进制表示? [英] How do I display the binary representation of a float or double?

查看:17
本文介绍了如何显示浮点数或双精度数的二进制表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示浮点数的二进制(或十六进制)表示.我知道如何手动转换(使用 here 方法),但是我有兴趣查看执行相同操作的代码示例.

I'd like to display the binary (or hexadecimal) representation of a floating point number. I know how to convert by hand (using the method here), but I'm interested in seeing code samples that do the same.

虽然我对 C++ 和 Java 解决方案特别感兴趣,但我想知道是否有任何语言使它特别容易,所以我将这种语言无关.我很想看到一些其他语言的解决方案.

Although I'm particularly interested in the C++ and Java solutions, I wonder if any languages make it particularly easy so I'm making this language agnostic. I'd love to see some solutions in other languages.

我已经很好地了解了 C、C++、C# 和 Java.是否有任何替代语言专家想要添加到列表中?

I've gotten good coverage of C, C++, C#, and Java. Are there any alternative-language gurus out there who want to add to the list?

推荐答案

C/C++ 很简单.

union ufloat {
  float f;
  unsigned u;
};

ufloat u1;
u1.f = 0.3f;

然后你就输出u1.u.你可以调整这个实现.

Then you just output u1.u. You can adapt this implementation.

翻倍同样简单.

union udouble {
  double d;
  unsigned long u;
}

因为双精度是 64 位的.

because doubles are 64 bit.

Java 稍微简单一些:使用 Float.floatToRawIntBits() 结合 Integer.toBinaryString()Double.doubleToRawLongBits 结合 Long.toBinaryString().

Java is a bit easier: use Float.floatToRawIntBits() combined with Integer.toBinaryString() and Double.doubleToRawLongBits combined with Long.toBinaryString().

这篇关于如何显示浮点数或双精度数的二进制表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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