Go Down

Topic: Really weird bug (Read 542 times) previous topic - next topic

Bernix

I'm trying to write some code to convert 4bytes to single float IEEE 754. The code looks like this:

Code: [Select]

float bytesToFloat(int a,int b,int c,int d) {
 long exponent;
 float mantissa;
 float result;
 float e23=8388608;
 exponent = (0x7F&a)<<1 | (0x80&b)>>7;
 mantissa = (0x7F&b)*pow(2,16) + c*pow(2,8) + d;
 result = (1+mantissa/e23)*pow(2,exponent-127)  
 return result;
}


The weird thing is that when I call this function I get ("the right result" -1) but if I write the calculation inside the loop() function the result is perfect!!!  :o

For example the following bytes: 41 - 60 - 00 - 00 should give as result 14 but I get 13 calling the function and 14 if I write it inside the function.

Here is a complete sample code for testing purposes:

Code: [Select]
/*
* Weird error
* by Jose A. Jimenez Berni
*
* Sample routine to convert from bytes to IEEE754 single float
* The results are different if the routine is inside the loop
* or it is called as a function...
*
*/

#include <math.h>
int ledPin = 13;                // LED connected to digital pin 13

void setup()                    // run once, when the sketch starts
{
 Serial.begin(9600);
 pinMode(ledPin, OUTPUT);      // sets the digital pin as output
}

void loop()                     // run over and over again
{
 digitalWrite(ledPin, HIGH);   // sets the LED on
 delay(1000);                  // waits for a second
 digitalWrite(ledPin, LOW);    // sets the LED off
 delay(1000);                  // waits for a second
 int a,b,c,d;
 long exponent;
 float mantissa;
 float result;
 float e23=8388608;
 a=0x41;
 b=0x60;
 c=0x00;
 d=0x00;
 exponent = (0x7F&a)<<1 | (0x80&b)>>7;
 Serial.print("Inside the Loop -> Exponent: ");
 Serial.print(exponent,DEC);  
 mantissa = (0x7F&b)*pow(2,16) + c*pow(2,8) + d;
 Serial.print(" / Mantissa: ");
 Serial.print(mantissa,DEC);  
 result = (1-2*(0x80&a))*(1+mantissa/e23)*pow(2,exponent-127);
 Serial.print(" / Result: ");
 Serial.println(result,DEC);
 result = bytesToFloat(a,b,c,d);

}

float bytesToFloat(int a,int b,int c,int d) {
 long exponent;
 float mantissa;
 float result;
 float e23=8388608;
 exponent = (0x7F&a)<<1 | (0x80&b)>>7;
 Serial.print("Inside the Fuction -> Exponent: ");
 Serial.print(exponent,DEC);  
 mantissa = (0x7F&b)*pow(2,16) + c*pow(2,8) + d;
 Serial.print(" / Mantissa: ");
 Serial.print(mantissa,DEC);  
 result = (1-2*(0x80&a))*(1+mantissa/e23)*pow(2,exponent-127);
 Serial.print(" / Result: ");
 Serial.println(result,DEC);    
 return result;
}


Here is the output:

Inside the Loop -> Exponent: 130 / Mantissa: 6291456 / Result: 14

Inside the Fuction -> Exponent: 130 / Mantissa: 6291456 / Result: 13


Any ideas?

Go Up