问题
i want to convert int to char
* in C without using itoa()
function.
Because on my Linux Systems i itoa
function is not there. i am using this code which i found from here
I want to run this function on Embedded devices also which are using Linux.
So i am looking for without use of itoa
.
I dnt want to use sprintf
also because its uses for just prints.
So any body please help me to figured out this problem.
Thanks
回答1:
Thing is snprintf
is the perfect function for this:
char str[LEN];
snprintf(str, sizeof(str), "%d", num);
回答2:
Here is a simple snippet you can use. There are more elegant and advanced ways, but this gets the job done.
In embedded projects in the past, I have measured this to be approximately 1000 times more efficient than sprintf(). This code is also MISRA-C compliant.
void getDecStr (uint8_t* str, uint8_t len, uint32_t val)
{
uint8_t i;
for(i=1; i<=len; i++)
{
str[len-i] = (uint8_t) ((val % 10UL) + '0');
val/=10;
}
str[i-1] = '\0';
}
回答3:
I find an implemantation of itoa from this link. Maybe it helps you as it did for me.
回答4:
#include <stdio.h>
#include <string.h>
#if 0
char *strrev(char *str){
char c, *front, *back;
if(!str || !*str)
return str;
for(front=str,back=str+strlen(str)-1;front < back;front++,back--){
c=*front;*front=*back;*back=c;
}
return str;
}
#endif
char *itoa(int v, char *buff, int radix_base){
static char table[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char *p=buff;
unsigned int n = (v < 0 && radix_base == 10)? -v : (unsigned int) v;
while(n>=radix_base){
*p++=table[n%radix_base];
n/=radix_base;
}
*p++=table[n];
if(v < 0 && radix_base == 10) *p++='-';
*p='\0';
return strrev(buff);
}
int main ()
{
int i;
char str[33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,str,10);
printf ("decimal: %s\n", str);
itoa (i, str, 16);
printf ("hexadecimal: %s\n", str);
itoa (i, str, 2);
printf ("binary: %s\n", str);
return 0;
}
回答5:
I found solution regarding this..
I am Happy to and i want which i expected.
#include <string.h>
#include <stdlib.h>
char *i_to_a(int num);
int main()
{
char *str = i_to_a(4567);
printf("%s",str);
free(str);
str = NULL;
return 0;
}
int no_of_digits(int num)
{
int digit_count = 0;
while(num > 0)
{
digit_count++;
num /= 10;
}
return digit_count;
}
char *i_to_a(int num)
{
char *str;
int digit_count = 0;
if(num < 0)
{
num = -1*num;
digit_count++;
}
digit_count += no_of_digits(num);
str = malloc(sizeof(char)*(digit_count+1));
str[digit_count] = '\0';
while(num > 0)
{
str[digit_count-1] = num%10 + '0';
num = num/10;
digit_count--;
}
if(digit_count == 1)
str[0] = '-';
return str;
}
来源:https://stackoverflow.com/questions/9994742/want-to-convert-integer-to-string-without-itoa-function