FloatToInt32Bits and Int32BitsToFloat

  • Thread starter Thread starter Paul Selormey
  • Start date Start date
P

Paul Selormey

Hello All,
I need safe functions like "FloatToInt32Bits" and "Int32BitsToFloat",
equivalent of the "BitConverter.DoubleToInt64Bits()" and
"BitConverter.Int64BitsToDouble()"

Any help?

Best regards,
Paul.
 
Paul,
I need safe functions like "FloatToInt32Bits" and "Int32BitsToFloat",
equivalent of the "BitConverter.DoubleToInt64Bits()" and
"BitConverter.Int64BitsToDouble()"

int i = BitConverter.ToInt32(BitConverter.GetBytes(float));

float f = BitConverter.ToSingle(BitConverter.GetBytes(int));



Mattias
 
Hello Mattias,
Thanks for the support. I found a different way to solve the
actual problem, but this information is still valuable - thanks.

Best regards,
Paul.
 
I've come across the same problem when trying to test for negative zero. Here's a heavy handed solution, not one you're going to use for performance

public class BitConverterAgai

[System.Runtime.InteropServices.StructLayout
System.Runtime.InteropServices.LayoutKind.Explicit)
private struct SingleAndInt32Union

[System.Runtime.InteropServices.FieldOffset(0)
public System.Single single

[System.Runtime.InteropServices.FieldOffset(0)
public System.Int32 int32


[System.ThreadStatic
static SingleAndInt32Union union

// until C#2.0 and static classes come around, we'll do thi
private BitConverter2() {

/// <summary
/// Converts the specified single-precision floating point number to a
/// 32-bit signed integer
/// </summary
/// <param name="value">The number to convert.</param
/// <returns>A 32-bit signed integer whose value is equivalent to value
/// </returns
public static System.Int32 SingleToInt32Bits(System.Single value

union.single = value
return union.int32


/// <summary
/// Converts the specified 32-bit signed integer to a single-precisio
/// floating point number
/// </summary
/// <param name="value">The number to convert.</param
/// <returns>A single-precision floating point number whose value is
/// equivalent to value.</returns
public static System.Single Int32BitsToSingle(System.Int32 value

union.int32 = value
return union.single
 
Back
Top