c# - 将 byte[] 转换为数组问题

标签 c# floating-point marshalling bitconverter

请检查此代码

float f = BitConverter.ToSingle(new byte[] { 0xBF, 0x04, 0x8E, 0xFF }, 0);
byte[] b = BitConverter.GetBytes(f);

这会产生一个奇怪的结果。 b 将是 { 0xBF, 0x04, 0xCE, 0xFF }

我猜是因为 f 的值为 NaN。 我问这个问题的原因是因为我使用 Marsal 将字节流转换为包含 float 的结构,我交换字节序

事情是当我到达现场时已经搞砸了(就像上面的例子)

有什么想法吗?

谢谢!

最佳答案

由于您的问题似乎是字节序的,我想知道是否检查 NaN 并反转顺序并设置一个 bool 值以在必要时反转它,是否会有所帮助:

byte[] input = { 0xBF, 0x04, 0x8E, 0xFF };
bool reversed = false;
float f = BitConverter.ToSingle(input, 0);

if (float.IsNaN(f))
{
    reversed = true;
    f = BitConverter.ToSingle(input.Reverse().ToArray(), 0);
}

byte[] b = BitConverter.GetBytes(f);

if (reversed)
    b = b.Reverse().ToArray();

关于c# - 将 byte[] 转换为数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20260942/

相关文章:

c# - 在 C# 中对字符串数组进行插入排序

c# - 如何改进 C# 中 get 调用方法的代码

仅使用按位操作将 float 转换为 int (float2int)

language-agnostic - 通用语言中的实数算术?

namespaces - JAXB Impl 在编码的 xml 中生成不正确的命名空间

c# - C# 中的 Mysql 查询

c# - C++/命令行界面 : functions inherited from template class are not visible in C#

f# - 用可区分联合和记录类型表示浮点

c# - 如何将自定义结构对象从 C++ COM 组件返回并使用到 C# 应用程序中

json - 如何在 GO 中包含一个数组作为结构定义的一部分?