edk

float value를 string으로 바꿔주는 함수 및 사용법

xilinx 2012. 1. 10. 15:05
#include <math.h>

char *int_str (int value, int width, int trim)
{
static char asc_string[21]; // string to be built
int digit,save_value,i,j;
char sign;

if (width > 10) 
width = 10; // Set maximum number length

save_value = value; // save a copy of the initial number
value = abs(value); // take absolute value
// loop extracting BCD digits
for (i=1; i<=width; i++) {
digit = value % 10; // extract low order digit
asc_string[width - i] = digit+0x30;
value = value / 10;
}
asc_string[width]=0; // add string terminator

// trim leading zeros and insert sign if trim is true
if (trim == 1) {
// search for first significant digit
for (i=0; i< (width-1); i++)
if (asc_string[i] != (char) 0x30) break;
// insert the sign if negative
if (save_value < 0) {
i --;
asc_string[i] = (char) "-"; // insert the sign
}
// copy string left adjusted
for (j = 0; j <= (width - i); j++)
asc_string [j] = asc_string [j+i];
}
return asc_string;
}

// Int_Str -- convert binary number to signed BCD string equivalent
// with no leading zeros
char *int_str_trim (int value)
{
return int_str (value, 10, 1);
}


void *float_to_string(float val, int dp)
{
int dpVal=1;
int dp1, intPart, fracPart;
static char asc_string[41]; // string to be built

if(dp>8) dp=8;         // set a maximum number of decimal places
dp1 = dp;
intPart=(int)val;
//Extract the fractional part
//Generate the required scale factor
while (dp1>0) {
dpVal=dpVal*10;
dp1--;
}
// Compute fraction
fracPart =(int) fabsf((val - intPart) *dpVal + 0.5F);
strcpy(asc_string, int_str_trim (intPart)); // place integer portion in string
strcat(asc_string, "."); // add decimal
strcat(asc_string, int_str (fracPart,dp,0)); // extract the decimal portion
return asc_string;
}

void main()
{
float a, b, c;
    float d, e;

a = 3.0;
b = 2.1;
c = a/b;
    d = log10f(100.0); 
e = powf(10.0, 2.2);
a = expf(4.0);
xil_printf("\n\r%s", float_to_string(d, 2));
xil_printf("\n\r%s", float_to_string(e, 2));
xil_printf("\n\r%s", float_to_string(a, 2));
}