CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to CCS Technical Support

Float to byte conversion

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
tahiticecil



Joined: 30 Aug 2010
Posts: 2

View user's profile Send private message

Float to byte conversion
PostPosted: Mon Aug 30, 2010 5:36 am     Reply with quote

Hello everyone !

I would like to know how to convert a float number (value is always between 0 and 255) to a byte like this :
Float value 5,023 should be converted to 5 in my byte, 127.845 => 127 etc.

Any ideas ?
Best Regards,
Clément.
mkuang



Joined: 14 Dec 2007
Posts: 257

View user's profile Send private message Send e-mail

PostPosted: Mon Aug 30, 2010 7:23 am     Reply with quote

You mean just keep the integer part of it?

You can do:

Code:

unsigned char my_integer;
float my_float;
.
.
.
my_integer = (unsigned char) my_float;
SherpaDoug



Joined: 07 Sep 2003
Posts: 1640
Location: Cape Cod Mass USA

View user's profile Send private message

PostPosted: Mon Aug 30, 2010 3:54 pm     Reply with quote

In the general C language lingo you want to "cast" the float to an 8 bit int. The compiler should do this automatically, but to be really sure you can do what mkuang shows.

This

my_integer = (unsigned char) my_float;

is an explicit cast, whereas simply

my_integer = my_float;

should do an automatic cast.
_________________
The search for better is endless. Instead simply find very good and get the job done.
tahiticecil



Joined: 30 Aug 2010
Posts: 2

View user's profile Send private message

PostPosted: Tue Aug 31, 2010 5:23 am     Reply with quote

Hi !

I hadn't thought that a simple cast could work. I tried to work directly on each bytes of a float var to get the integer part.


Thank you for your help.
Clément
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
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