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