Bytes to float...

Started by
8 comments, last by darookie 18 years, 3 months ago
how do you convert from an array of 4 bytes to a float? Thanks, Devin
Advertisement
char a[4]={0,0,0,0};
float f;
f=*reinterpret_cast<float*>(a);

Correct me if I'm wrong, anyone.
langauge?

in c and many of its offspring itll look like

// one 4 byte arraychar bytearray[4];float f = *((float*)bytearray);// many floatschar byteArray[4 * numFloats];float * floatArray = (float*)byteArray;float f = floatArray[ index ];


EDIT: fixed horrible error!
better question: why do you want to?
Quote:Original post by RDragon1
better question: why do you want to?
I assume it's either for serialization purposes or to perform bithacks on the integer representation of a float.
Either way it's fairly common thing to do..
trying to convert a dang mesh vertexbuffer into vector3's

thanks for your guys help,

-Devin
Quote:Original post by devronious
trying to convert a dang mesh vertexbuffer into vector3's
Any particular reason you can't just cast a pointer directly instead?
At least dealing with the structures at the byte level shouldn't be necessary as long as you're storing regular 32-bit floats in both.
the Mesh.LockVertexBuffer() method returns a byte array. For what I have figured out so far, I have to use the vertexDeclaration of the mesh to walk thru the byte data to determine what's what.

Any easier ideas are most certainly appreciated. But still it would be nice to know how to convert from four bytes to a float.

I'm using c# and I tried:

byte[] ba = {100, 1, 114, 123};
float f = (float)ba;

and it says can't convert.

-Devin
Quote:Original post by devronious
Any easier ideas are most certainly appreciated. But still it would be nice to know how to convert from four bytes to a float.

I'm using c# and I tried:

byte[] ba = {100, 1, 114, 123};
float f = (float)ba;

and it says can't convert.

-Devin


This may not be the most efficient way, but it sure is easy.
byte[] ba = {250,62,246,66};float f = System.BitConverter.ToSingle(ba,0);  // f now equals 123.123F
Use a GraphicStream, you can use that with a BinaryReader/-Writer as well.

HTH,
Pat.

This topic is closed to new replies.

Advertisement