将浮点数转换为等效整数
我想将浮点用户输入转换为其等效的整数。我可以通过接受输入字符串(例如“-1.234”)来做到这一点,然后我可以将每个字符显式转换为其十进制表示形式。 (顺便说一下大端)。所以我只想说,对于我给出的例子,
-1.234 = 1|01111111|00111011111001110110110
sign bit = 1 = 128<<31
exponent bits = 01111111 = 127<<23
mantissa bits = 00111011111001110110110 = 1962934
decimal equivalent = 1962934 + 127<<23 + 128<<31
这很简单,但很笨拙。有更好的方法吗?也许我可以做某种类型转换?
I want to convert a floating point user input into its integer equivalent. I could do this by accepting an input string, say "-1.234" and then I could just explicitly convert each character to it's decimal representation. (big endian by the way). So I would just say for the example I gave,
-1.234 = 1|01111111|00111011111001110110110
sign bit = 1 = 128<<31
exponent bits = 01111111 = 127<<23
mantissa bits = 00111011111001110110110 = 1962934
decimal equivalent = 1962934 + 127<<23 + 128<<31
This is easy enough but unwieldy. Is there a better way to do this? Maybe some sort of type casting I can do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
联合允许您访问同一块内存作为不同类型
警告:由于大小和对齐方式,您可能会遇到奇怪的平台差异和类似的事情,但因为您已经通过尝试将浮点解释为 int 做出了一些假设,你也许能够逃脱惩罚。了解更多有关工会的信息,我想这就是您想要的。
A union lets you access the same piece of memory as different types
warning: you can get into weird platform differences and things like that because of size and alighnment, but since you're already making some assumptions by trying to interpret the float as an int, you may be able to get away with it. Read more about unions, I think that's what you're going to want.
另外,在 C++ 中,有一个不执行任何检查的转换运算符
reinterpret_cast
。这里可能更好。Also, in C++ there's this conversion operator that doesn't do any checks,
reinterpret_cast
. It's probably better here.重新解释位模式的标准方法是使用 memcpy。如果我没记错的话,gcc 允许指针类型转换
*(int*)&a
作为扩展,但它不受标准保证,并且不适用于所有编译器。同样,工会也不能保证正常运作。通过优化,对 memcpy 的调用将从生成的机器代码中完全消除。
The standard way to re-interpret bit patterns is to use memcpy. If I recall correctly, gcc allows the pointer-type-casting
*(int*)&a
as extension, but it is not guaranteed by the standard, and does not work with all compilers. Similarly, unions are not guaranteed to work.With optimization, the call to memcpy will be completely eliminated from the generated machine code.
如果您需要转换一个简单的值,而不需要额外的变量:
In case you needed to convert a simple value, without an additional variable: