|
|
View previous topic :: View next topic |
Author |
Message |
evsource
Joined: 21 Nov 2006 Posts: 129
|
float to int question |
Posted: Tue Sep 01, 2009 6:23 pm |
|
|
Hi,
I know I can cast a float to an int, e.g:
Code: |
int the_int;
float the_float;
the_float = 8.5;
the_int = (int) the_float;
|
... and the result will be "8".
However, if I have a float variable that is percentages, and want to do a fast conversion on a 18F chip to an int, how can I do that?
If I cast the float to an int, anything below 100% will be 0. Sure, I can multiply by 100, then cast to an int, but on a 18F chip at 40mHz, that's going to cost me about 35us ... too long.
Any suggestions? |
|
|
vinniewryan
Joined: 29 Jul 2009 Posts: 154 Location: at work
|
|
Posted: Tue Sep 01, 2009 6:40 pm |
|
|
You could do Code: | the_int=(100 - the_float) | which would return a value you can work with, if indeed 100% is the greatest value the_float will hold. |
|
|
evsource
Joined: 21 Nov 2006 Posts: 129
|
|
Posted: Tue Sep 01, 2009 9:39 pm |
|
|
vinniewryan wrote: | You could do Code: | the_int=(100 - the_float) | which would return a value you can work with, if indeed 100% is the greatest value the_float will hold. |
Hmm... I'm not sure that's what I'm after.
e.g.
Code: |
the_float = 0.08; // 8%
the_int = (int)(100 - the_float); |
the_int will be "99" if I understand things correctly. The desired result is "8".
Just some background, the value that is a float needs to be transmitted over a serial communications line. I know I could do fixed-point arithmetic to avoid using the float altogether, but it seems like the right thing to do in code, using the float. But to transmit it, I only want to send one byte, since all I want in the transmitted data is 0-100%, in integer increments.
I was just curious if there was a way to get the float into an integer in less than 35us on a 40mHz 18F chip. |
|
|
vinniewryan_guest Guest
|
|
Posted: Wed Sep 02, 2009 12:03 am |
|
|
Oh I see, I didn't realize you would be working with numbers less than 1. Now that I think about it, it was just an overall thoughtless answer.
I can't think of any other methods of rounding a percent to a whole number without multiplying. Sorry. |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|