如何使用实际逻辑将float转换为byte []。 [英] How do I convert float to byte[] by using actual logic.
本文介绍了如何使用实际逻辑将float转换为byte []。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,
除了使用内置方法
Hello,
I need to convert float number to byte[] apart from using inbuilt method
BitConverter.GetBytes
之外,我需要将浮点数转换为byte []。我想用一些逻辑来实现这个目标。
谢谢。
我是什么尝试过:
谷歌搜索,但除了内置方法之外无法找到任何东西
. I want to achieve this by using some logic.
Thank you.
What I have tried:
I googled, but was unable to find anything apart from the builtin method
BitConverter.GetBytes
。
.
推荐答案
这在C#中很复杂,因为在C#中将双精度转换为字节友好值不是可能在普通代码中。
如果你看一下参考源,你可以看看他们是怎么做的 - 而且很简单:
That's complicated in C#, because casting doubles to "byte friendly" values in C# isn't possible in "normal" code.
If you have a look at the Reference Sources however, you can see how they do it - and it's pretty simple:
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(double value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
return GetBytes(*(long*)&value);
}
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe static byte[] GetBytes(long value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
byte[] bytes = new byte[8];
fixed(byte* b = bytes)
*((long*)b) = value;
return bytes;
}
这是最有效的方法(忽略合约位)
但不安全
代码可能不是你的家庭作业要求...
That's the most efficient way to do it (ignore the Contract bits)
But unsafe
code may not be what your homework asks for either...
这篇关于如何使用实际逻辑将float转换为byte []。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文