float from bytes
-
Hi, I need to convert 4 bytes in to a float or double in C#. The 4 bytes come from the comm port and are read in to a byte array, how can I convert back to a float?
“If I had asked people what they wanted, they would have said faster horses.” ― Henry Ford
-
Hi, I need to convert 4 bytes in to a float or double in C#. The 4 bytes come from the comm port and are read in to a byte array, how can I convert back to a float?
“If I had asked people what they wanted, they would have said faster horses.” ― Henry Ford
Try BitConverter.ToSingle[^] - can't guarantee it will work, it depends on the originator floating point format. If it give ridiculous values, try swapping the byte order: ABCD -> DCBA Then try it again.
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
-
Hi, I need to convert 4 bytes in to a float or double in C#. The 4 bytes come from the comm port and are read in to a byte array, how can I convert back to a float?
“If I had asked people what they wanted, they would have said faster horses.” ― Henry Ford
You could also try:
int res = 0;
if (littleEndian)
{
res += b[0];
res += (((int)b[1]) << 8);
res += (((int)b[2]) << 16);
res += (((int)b[3]) << 24);
}
else
{
res += b[3];
res += (((int)b[2]) << 8);
res += (((int)b[1]) << 16);
res += (((int)b[0]) << 24);
}float f;
f = Convert.ToSingle(res);Of course, littleendian needs to be defined and assigned earlier. Converting to double is similar - you need to replace int by long and use Convert.ToDouble(res).
-
You could also try:
int res = 0;
if (littleEndian)
{
res += b[0];
res += (((int)b[1]) << 8);
res += (((int)b[2]) << 16);
res += (((int)b[3]) << 24);
}
else
{
res += b[3];
res += (((int)b[2]) << 8);
res += (((int)b[1]) << 16);
res += (((int)b[0]) << 24);
}float f;
f = Convert.ToSingle(res);Of course, littleendian needs to be defined and assigned earlier. Converting to double is similar - you need to replace int by long and use Convert.ToDouble(res).
-
You could also try:
int res = 0;
if (littleEndian)
{
res += b[0];
res += (((int)b[1]) << 8);
res += (((int)b[2]) << 16);
res += (((int)b[3]) << 24);
}
else
{
res += b[3];
res += (((int)b[2]) << 8);
res += (((int)b[1]) << 16);
res += (((int)b[0]) << 24);
}float f;
f = Convert.ToSingle(res);Of course, littleendian needs to be defined and assigned earlier. Converting to double is similar - you need to replace int by long and use Convert.ToDouble(res).