goo*_*ate 45 .net c# floating-point bytearray endianness
我有一个Floats数组需要转换为字节数组并返回到float [] ...任何人都可以帮我正确地执行此操作吗?
我正在使用bitConverter类,发现自己试图追加结果.
我这样做的原因是我可以将运行时值保存到IO流中.如果重要,目标存储是Azure页面blob.我不关心它存储在哪个endian,只要它输入与输出匹配.
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 }
Run Code Online (Sandbox Code Playgroud)
Luk*_*keH 80
如果您正在寻找性能,那么您可以使用Buffer.BlockCopy.很好,很简单,可能和托管代码一样快.
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
Run Code Online (Sandbox Code Playgroud)
有BitConverter.ToSingle(byte[] value, int startIndex) 一种方法应该在这里有所帮助。
返回从字节数组中指定位置的四个字节转换而来的单精度浮点数。
你可能想要这样的东西(未经测试):
static float[] ConvertByteArrayToFloat(byte[] bytes)
{
if(bytes == null)
throw new ArgumentNullException("bytes");
if(bytes.Length % 4 != 0)
throw new ArgumentException
("bytes does not represent a sequence of floats");
return Enumerable.Range(0, bytes.Length / 4)
.Select(i => BitConverter.ToSingle(bytes, i * 4))
.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
编辑:非 LINQ:
float[] floats = new float[bytes.Length / 4];
for (int i = 0; i < bytes.Length / 4; i++)
floats[i] = BitConverter.ToSingle(bytes, i * 4);
return floats;
Run Code Online (Sandbox Code Playgroud)
当你将float [i]复制到字节数组中时,你没有移动位置,你应该写类似的东西
Array.Copy(BitConverter.GetBytes(float[i]),0,res,i*4);
Run Code Online (Sandbox Code Playgroud)
而不只是:
ret = BitConverter.GetBytes(floats[i]);
Run Code Online (Sandbox Code Playgroud)
反函数遵循相同的策略.