0

For some calculations I need to use Floats, but I have an byte[] at my disposal so I first do:

Array.Copy(byteArray, floatArray, byteArray.Length);

That works great, I the do some calulations on the floats.but now I need to convert it back to an byteArray. I can't use the following code, it crashes, without giving an specific error message.

float[] DiffernetfloatArray= new float[ byteArray];  
Array.Copy(DiffernetfloatArray, byteArray, DiffernetfloatArray.Length);

First I thought it was the size that wasn't OK, but the float array that I'm using, I increased the size by 500 just for testing, still gave me same error

Does anyone know how I could fix this? Preferably answers in C#

Security Hound
  • 2,577
  • 3
  • 25
  • 42
Kiwi
  • 2,713
  • 7
  • 44
  • 82

3 Answers3

4

its easier with linq:

var byteArray = floatArray.Select(f => Convert.ToByte(f)).ToArray();
var floatArray = byteArray.Select(b => (float)Convert.ToDouble(b)).ToArray();
lante
  • 7,192
  • 4
  • 37
  • 57
2

There's an easier way:

System.BitConverter.GetBytes(float)

MSDN

Sten Petrov
  • 10,943
  • 1
  • 41
  • 61
-2

A byte can be converted to a float as it will fit within the type, but going the other way cannot be done with an implicit conversion - a float may be far too big to fit into a byte, therefore an Array.Copy will never work in this scenario.

cjk
  • 45,739
  • 9
  • 81
  • 112