View previous topic :: View next topic |
Author |
Message |
asmallri
Joined: 12 Aug 2004 Posts: 1634 Location: Perth, Australia
|
float manipulation problem |
Posted: Thu Jul 01, 2010 6:41 am |
|
|
I need to put a float value into a int32 value for transport to another PIC.
However I am doing something wrong with my pointer manipulation. Here is a sample code segment that demonstrates the problem
Code: |
float sensor_data; // this is the variable we want to print
unsigned int32 *data_ptr; // pointer we are manipulating
sensor_data = 123.456; // initialize the variable to a known value
// print the size of float to make sure it is 32 bits
printf("Size of Float = %u\r\n", sizeof(float));
// point to sensor_data
data_ptr = (unsigned int32*)&sensor_data;
// show the contents of the location pointed to by data_ptr
printf("*data_ptr = %e\r\n", (float)*data_ptr);
// show the contents of sensor_data
printf("sensor_data = %e\r\n", sensor_data);
|
Here is the output from printf
Size of Float = 4
*data_ptr = 2.045343E+09
sensor_data = 1.234559E+02
Can anyone see what I am doing wrong?
I am using PCH and have tested this on version 4.084 and 4.107 _________________ Regards, Andrew
http://www.brushelectronics.com/software
Home of Ethernet, SD card and Encrypted Serial Bootloaders for PICs!! |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19515
|
|
Posted: Thu Jul 01, 2010 6:54 am |
|
|
The problem is that 'data_ptr', is a pointer to an int32.
You get the contents of this pointer (an int32 value), then convert the _result_ to a float.
You have already retrieved the int32, before you perform the cast to float...
As a comment, this is a perfect excuse for a union.
Code: |
union converter {
float fpval;
int32 int32val;
} value;
int32 temp;
value.fpval=123.45;
//You can then send the 32bit value, by accessing value.int32val.
temp=value.int32val; //How to access the int32 val
value.int32val=0; //Clear the value
printf("Int32 value representing the float %lu\n\r", temp);
value.int32=temp; //Put the value back
printf("float value represented by int32 value above %e\n\r",value.fpval);
//and show the FP result.
|
Best Wishes |
|
|
Jerson
Joined: 31 Jul 2009 Posts: 125 Location: Bombay, India
|
|
Posted: Thu Jul 01, 2010 7:36 am |
|
|
you can do this
Code: | // show the contents of the location pointed to by data_ptr
printf("*data_ptr = %e\r\n", *(float *)data_ptr);
|
ps: I see you posted synchronously with me _________________ Regards
Jerson Fernandes
Last edited by Jerson on Thu Jul 01, 2010 7:38 am; edited 1 time in total |
|
|
asmallri
Joined: 12 Aug 2004 Posts: 1634 Location: Perth, Australia
|
|
|
|