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,511
  • 3
  • 24
  • 41
Kiwi
  • 2,615
  • 5
  • 40
  • 75

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
  • 6,970
  • 2
  • 35
  • 56
2

There's an easier way:

System.BitConverter.GetBytes(float)

MSDN

Sten Petrov
  • 10,787
  • 1
  • 43
  • 57
-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
  • 44,524
  • 9
  • 79
  • 111