NI Home > Community > NI Discussion Forums

LabWindows/CVI

Reply
Member
jwinterb
Posts: 73
0 Kudos

Convert int to float

How do I properly convert an int to a float?

I input a number such as 0x42c26163

The final number should be 97.19021

I thought I could just do a cast so I tried this:

int test = 0x42c26163;

float test2 = (float)test;

But test2 comes up 1.120035171 E9

How do I get to the final 97.19021?

 

In another project I'm working on using C#, the conversion works when I use the BitConverter class.

 

I'm sure I am just overlooking the obvious, but can someone can help me?

Proven Zealot
RobertoBozzolo
Posts: 5,199
0 Kudos

Rif.: Convert int to float

I suppose that int number is really the content of a float read back from raw memory or received from an instrument or on some communication channel. Rebuilding the float number has been discussed a couple of ways in the forums: I can suggest you look at this thread or this other one which give you feasible solutions.

This is basically a reflect of how floating point numbers are stored in memory according to IEEE754 standard, which you may want to take a look at to understand a bit how all the matter is treated.



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Zone Community
________________________________________
If I have helped you, why not giving me a kudos?
Active Participant
msaxon
Posts: 419
0 Kudos

Re: Convert int to float

You can do:

 

int test = 0x42c26163;
float test2 = *(float *)&test;

 Or you could fiddle about with a union.

--
Martin
Certified CVI Developer
Member
jwinterb
Posts: 73
0 Kudos

Re: Convert int to float

Thank You, that works great!

What exactly does *(float *) mean?

 

Thanks
JW

 

Active Participant
hendra@ngms
Posts: 208
0 Kudos

Re: Convert int to float

I use this kind of construction a lot particulary because it allows you to assign integers to bit structures, and retrieve integers from bit structures.

 

Read it as, "the value that is pointed to, by the float pointer that points to, the integer at this address".

 

It sounds like the same thing as casting a float, but I think there are compiler issues with getting the right number of bytes assigned.  The pointer trick fixes that. 

Member
OVR_CZ
Posts: 96
0 Kudos

Re: Convert int to float

maybe better definition:Get pointer to memory "&test" a and interpret it as pointer to float "(float *)" then get value from this pointer "*"

Active Participant
menchar
Posts: 1,140
0 Kudos

Re: Convert int to float

Cast a pointer to be of type "pointer to float" and then de-reference it.