Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Char into Float

How to convert an unsigned char value into a float or double in coding in AVR studio 4.?

Please help I am a beginner, my question may sound stupid too :/

Like I have got a char keyPressed

and I have printed it on the screen using lcd_gotoxy(0,0); lcd_puts (keyPressed);

Now I want to use this value to calculate something.. How to convert it into float or double? please help

like image 698
Mohit Goyal Avatar asked Aug 28 '13 17:08

Mohit Goyal


People also ask

Can you convert char to float in C?

The C library function double atof(const char *str) converts the string argument str to a floating-point number (type double).

How do you convert a string to a float?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

Can you convert a char to a string?

You can use String(char[] value) constructor to convert char array to string. This is the recommended way.


2 Answers

if you want for example character 'a' as 65.0 in float then the way to do this is

unsigned char c='a';
float f=(float)(c);//by explicit casting
float fc=c;//compiler implicitly convert char into float.

if you want for example character '9' as 9.0 in float then the way to do this is

unsigned char c='9';
float f=(float)(c-'0');//by explicit casting
float fc=c-'0';//compiler implicitly convert char into float.

if you want to convert character array containing number to float here is the way

#include<string>
#include<stdio.h>
#include<stdlib.h>
void fun(){
unsigned char* fc="34.45";
//c++ way
std::string fs(fc);
float f=std::stof(fs);//this is much better way to do it
//c way
float fr=atof(fc); //this is a c way to do it
}

for more refer to link: http://en.cppreference.com/w/cpp/string/basic_string/stof http://www.cplusplus.com/reference/string/stof/

like image 190
Himanshu Pandey Avatar answered Oct 21 '22 21:10

Himanshu Pandey


For character array input you can use atof.

like image 24
Don't You Worry Child Avatar answered Oct 21 '22 23:10

Don't You Worry Child