Convert int bits to float bits

前端 未结 6 1280
醉话见心
醉话见心 2020-12-04 02:50

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

6条回答
  •  心在旅途
    2020-12-04 03:16

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

提交回复
热议问题