Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

c# - Convert int bits to float bits

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.

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;
}

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...