intBitsToFloat method in Java VS C#?

前端 未结 3 419
猫巷女王i
猫巷女王i 2021-01-26 16:34

I\'m getting the wrong number when converting bits to float in C#.

Let\'s use this bit number= 1065324597

In Java, if I want to co

相关标签:
3条回答
  • 2021-01-26 17:18

    Just try this...

    var myBytes = BitConverter.GetBytes(1065324597);
    var mySingle = BitConverter.ToSingle(myBytes,0);
    

    The BitConverter.GetBytes converts your integer into a four byte array. Then BitConverter.ToSingle converts your array into a float(single).

    0 讨论(0)
  • 2021-01-26 17:21

    i want to add on top of what jon skeet said, that also, for big float, if you don't want the "E+" output you should do:

    intbits.ToString("N0");
    
    0 讨论(0)
  • 2021-01-26 17:23

    Just casting is an entirely different operation. You need BitConverter.ToSingle(byte[], int) having converted the int to a byte array - and possibly reversed the order, based on the endianness you want. (EDIT: Probably no need for this, as the same endianness is used for both conversions; any unwanted endianness will just fix itself.) There's BitConverter.DoubleToInt64Bits for double, but no direct float equivalent.

    Sample code:

    int x = 1065324597;
    byte[] bytes = BitConverter.GetBytes(x);
    float f = BitConverter.ToSingle(bytes, 0);
    Console.WriteLine(f);
    
    0 讨论(0)
提交回复
热议问题