问题描述
我有花车的数组需要转换为字节数组,并返回一个float [] ...谁能帮我正确地做到这一点?
我的工作与bitConverter类,发现自己卡住试图追加的结果。
我这样做的原因是这样我就可以节省运行时间值转换为IO流。目标存储天青页斑点的情况下,重要的事情。我不关心什么尾数,这是储存在,只要输入输出相匹配。
静态的byte [] ConvertFloatToByteArray(浮动[]花车)
{
byte []的RET =新的字节[floats.Length * 4]; //一个单精度浮点数为4个字节/ 32位
的for(int i = 0; I< floats.Length;我++)
{
// TODO:卡住了......我需要追加的结果,一个RET偏移
RET = BitConverter.GetBytes(花车[I]);
}
返回RET;
}
静态浮动[] ConvertByteArrayToFloat(byte []的字节)
{ //去做 }
如果你正在寻找的性能,那么你可以使用<$c$c>Buffer.BlockCopy$c$c>.尼斯和简单,大概是快,你会得到管理code。
VAR floatArray1 =新的浮动[] {123.45f,123F,45F,1.2F,34.5f};
//创建一个字节数组,花车复制到它...
VAR的字节数组=新的字节[floatArray1.Length * 4]。
Buffer.BlockCopy(floatArray1,0,字节数组,0,byteArray.Length);
//创建第二个float数组和字节复制到它...
VAR floatArray2 =新的浮动[byteArray.Length / 4]。
Buffer.BlockCopy(字节数组,0,floatArray2,0,byteArray.Length);
//我们有我们开始用浮漂的相同顺序?
Console.WriteLine(floatArray1.SequenceEqual(floatArray2)); // 真正
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?
I'm working with the bitConverter class and found myself stuck trying to append the results.
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 }
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
这篇关于如何转换float数组以一个byte []和回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!