#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
char *strrev(char *src)
{
assert(src != NULL);
char *head = src;
char *tail = src;
char tmp;
/* tail指向src末尾*/
while (*tail++)
NULL;
tail--; //与tail++抵消
tail--; //跳过末尾 \0
/* 完成反转*/
while (head < tail)
{
tmp = *head;
*head++ = *tail;
*tail-- = tmp;
}
return src;
}
void uint_to_str(uint32_t u, char *str)
{
char *p = str;
do
{
*p++ = u % 10 + '0'; //数字变字符
}while ((u/=10) > 0);
*p = '\0';
str = strrev(str); //字符逆序
}
void int_to_str(int32_t i, char *str)
{
if (i < 0)
{
*str++ = '-';
i = -i;
}
//这里避免上溢
//即假设i是16位,则 i = -32768 时, -i = -32768
uint_to_str((uint32_t)i, str);
}
int32_t main(void)
{
char tmp[30] = {'\0'};
int32_t a = INT32_MAX, b = INT32_MIN;
//a为int最大值
int_to_str(a, tmp);
printf("a = %s\n", tmp);
//b为int最小值
memset(tmp, 0, 30);
int_to_str(b, tmp);
printf("b = %s\n", tmp);
return 0;
}
my_itoa
最新推荐文章于 2023-01-15 18:58:45 发布