Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the bits of a "double" as a "long"

I would like to manipulate the bitwise representation of floating-point numbers in C#. BinaryWriter and BinaryReader do it this way:

public virtual unsafe void Write(double value)
{
    ulong num = *((ulong*) &value);
    ...
}
public virtual unsafe double ReadDouble()
{
    ...
    ulong num3 = ...;
    return *((double*) &num3);
}

Is there a way to do this without unsafe code, and without the overhead of actually using BinaryWriter and BinaryReader?

like image 935
Qwertie Avatar asked Dec 17 '10 23:12

Qwertie


1 Answers

Are you trying to avoid unsafe code altogether, or do you just want an alternative to those specific methods on BinaryReader and BinaryWriter?

You could use BitConverter.DoubleToInt64Bits and BitConverter.Int64BitsToDouble, which are designed to do exactly what you need, although I think they use the same unsafe conversion behind-the-scenes as the BinaryReader/BinaryWriter methods.

like image 162
LukeH Avatar answered Oct 15 '22 13:10

LukeH