转换INT位漂浮位 [英] Convert int bits to float bits

查看:109
本文介绍了转换INT位漂浮位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建一个缓冲区,将读取的一面旗帜中,我可以完全根除自带的TCP分割的问题/写的过程。我遇到的唯一问题是浮点变量,一切工作正常,除了为浮动。我无法找到如何INT32位转换成浮动的任何信息。

I'm in the process of creating a buffer that will read/write in a banner in which I can completely eradicate the problems that comes with TCP-Segmentation. The only problem I've ran into is the float variable, everything else works fine, besides for the float. I can't find any information on how to convert int32 bits into a float.

在转换一个float到int位,下面的方法被用于(剥去直出Java的源$ C ​​$ C,并转化)

When converting a float to int bits, the following method is used (Ripped straight out of java's source code, and converted)

private int floatToIntBits(float value)
{
    int result = BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
    if (((result & 0x7F800000) == 0x7F800000) && (result & 0x80000000) != 0)
        result = 0x7fc00000;
    return result;
}

不过,现在我需要做相反的,不幸的是,没有在BitConverter类使用float适用于任何功能。

However, now I need to do the opposite, unfortunately, there isn't any functions in the BitConverter class that works with float.

我可以';吨要么找到JavaDoc中很多信息,而不是任何我个人可以使用,你可以找到的信息<一个href=\"http://grep$c$c.com/file/repository.grep$c$c.com/java/root/jdk/openjdk/8-b132/java/lang/Float.java#Float.intBitsToFloat%28int%29\"相对=nofollow>这里。

I can';t find much information in the JavaDocs either, not any that I can personally make use of, You can find info here.

推荐答案

难懂,如果你使用双击,有 BitConverter.DoubleToInt64Bits BitConverter.Int64BitsToDouble 。我真的不知道为什么有没有 / 的Int32 现金等价物,因为它迫使你创建一个毫无意义的字节[] 堆(它甚至不让你在pre-存在缓冲区传递)。

Vexingly, if you were using double and long, there is BitConverter.DoubleToInt64Bits and BitConverter.Int64BitsToDouble. I have genuinely no idea why there aren't Single / Int32 equivalents, as it forces you to create a pointless byte[] on the heap (it doesn't even let you pass in a pre-existing buffer).

如果你乐于使用不安全 code,你实际上可以做到这一切在一个简单的数据thunk的,没有任何方法调用或数组:

If you are happy to use unsafe code, you can actually do it all in a simply data thunk, without any method calls or arrays:

public static unsafe int SingleToInt32Bits(float value) {
    return *(int*)(&value);
}
public static unsafe float Int32BitsToSingle(int value) {
    return *(float*)(&value);
}

这篇关于转换INT位漂浮位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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