如何获取“双精度”的位数作为“长”
我想在 C# 中操作浮点数的按位表示。 BinaryWriter 和 BinaryReader 这样做是这样的:
public virtual unsafe void Write(double value)
{
ulong num = *((ulong*) &value);
...
}
public virtual unsafe double ReadDouble()
{
...
ulong num3 = ...;
return *((double*) &num3);
}
有没有一种方法可以在没有不安全代码的情况下做到这一点,并且没有实际使用 BinaryWriter 和 BinaryReader 的开销?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一种方法是使用具有显式布局的自定义结构,该结构在偏移量 0 处定义了
long
和double
。这相当于union
像这样的东西:
然后使用这个:
这将避免任何不安全的代码,并且当您在堆栈上执行转换时也应该执行得相当快。
我还没有尝试/编译过这个,但我认为它应该可以工作:)
编辑
我刚刚尝试过这个并且它有效。上面的
longBytes
的值是 4608236261112822104。一些其他值:
这是一个可以执行您想要的操作的方法:
Another way is to use a custom struct with explicit layout that defines both a
long
and adouble
at offset 0. This is equivalent to aunion
in C.Something like this:
Then use this:
This will avoid any unsafe code and should perform pretty fast too as you perform the conversion on the stack.
I haven't tried/compiled this but I reckon it should work :)
EDIT
I just tried this and it works. The value of
longBytes
above is 4608236261112822104.Some other values:
Here's a method that does what you want:
您是否试图完全避免不安全的代码,或者您只是想要替代
BinaryReader
和BinaryWriter
上的那些特定方法?您可以使用
BitConverter.DoubleToInt64Bits
和BitConverter.Int64BitsToDouble
,它们旨在完全满足您的需要,尽管我认为它们在幕后使用与BinaryReader
/BinaryWriter
方法相同的不安全转换。Are you trying to avoid unsafe code altogether, or do you just want an alternative to those specific methods on
BinaryReader
andBinaryWriter
?You could use
BitConverter.DoubleToInt64Bits
andBitConverter.Int64BitsToDouble
, which are designed to do exactly what you need, although I think they use the same unsafe conversion behind-the-scenes as theBinaryReader
/BinaryWriter
methods.您可以使用
byte[] BitConverter.GetBytes(double)
和long BitConverter.ToInt64(byte[],int)
(传递 0 作为起始索引),但是 < em>在内部 IIRC 这些使用不安全的代码,并且有数组的开销。选择你的毒药...You can use
byte[] BitConverter.GetBytes(double)
andlong BitConverter.ToInt64(byte[],int)
(passing 0 as the start-index), but internally IIRC these use unsafe code, plus have the overhead of an array. Pick your poison...