如何将浮点数组转换为 byte[] 并返回? [英] How do I convert an array of floats to a byte[] and back?

查看:37
本文介绍了如何将浮点数组转换为 byte[] 并返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Floats 数组,需要将其转换为字节数组并返回到 float[]... 谁能帮我正确地做到这一点?

I have an array of Floats that need to be converted to a byte array and back to a float[]... can anyone help me do this correctly?

我正在使用 bitConverter 类,但发现自己在尝试追加结果时卡住了.

I'm working with the bitConverter class and found myself stuck trying to append the results.

我这样做的原因是我可以将运行时值保存到 IO 流中.目标存储是 Azure 页面 blob,以防万一.我不关心它存储在什么字节序中,只要输入与输出匹配即可.

The reason I'm doing this is so I can save runtime values into a IO Stream. The target storage is Azure Page blobs in case that matters. I don't care about what endian this is stored in, as long as it input matches the output.

static  byte[] ConvertFloatToByteArray(float[] floats)
        {
            byte[] ret = new byte[floats.Length * 4];// a single float is 4 bytes/32 bits

            for (int i = 0; i < floats.Length; i++)
            {
               // todo: stuck...I need to append the results to an offset of ret
                ret = BitConverter.GetBytes(floats[i]);

            }
            return ret;
        }


 static  float[] ConvertByteArrayToFloat(byte[] bytes)
{ //to do }

推荐答案

如果您正在寻找性能,那么您可以使用 Buffer.BlockCopy.很好也很简单,可能和您在托管代码中获得的速度一样快.

If you're looking for performance then you could use Buffer.BlockCopy. Nice and simple, and probably about as fast as you'll get in managed code.

var floatArray1 = new float[] { 123.45f, 123f, 45f, 1.2f, 34.5f };

// create a byte array and copy the floats into it...
var byteArray = new byte[floatArray1.Length * 4];
Buffer.BlockCopy(floatArray1, 0, byteArray, 0, byteArray.Length);

// create a second float array and copy the bytes into it...
var floatArray2 = new float[byteArray.Length / 4];
Buffer.BlockCopy(byteArray, 0, floatArray2, 0, byteArray.Length);

// do we have the same sequence of floats that we started with?
Console.WriteLine(floatArray1.SequenceEqual(floatArray2));    // True

这篇关于如何将浮点数组转换为 byte[] 并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆