Created
December 13, 2015 14:49
-
-
Save zhanglongqi/f100ab01495483e9246c to your computer and use it in GitHub Desktop.
convert float to char, make transmission easier.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/* | |
* two ways of converting float to string or char | |
* | |
* */ | |
typedef union { | |
float f; | |
char c[4]; | |
} my_union_t; | |
// 1. | |
// using union to define new data type | |
// | |
// advantage here is the data will be exactly same between in original format, no need transition | |
// | |
void fun1() { | |
my_union_t u1; | |
u1.f = 3.9; | |
printf("float: %f\n char: %s \n", u1.f, u1.c); | |
} | |
// 2. | |
// using sprintf | |
// | |
// Advantage here is it will looked clearly for human | |
// | |
void fun2() { | |
float v_f = 4.8; | |
char c[20]; | |
sprintf(c, "%f", v_f); | |
printf("float: %f\n char: %s \n", v_f, c); | |
} | |
int main() { | |
fun1(); | |
fun2(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment