当前位置:网站首页>C语言(itoa函数)
C语言(itoa函数)
2022-07-22 10:35:00 【安若兮~】
itoa函数是将一个数字转化为其对应的进制数格式
例如 -10 转为10进制 -10
4转为2进制 100
其主要思想是 其中唯一的特殊情况是负数的十进制形式,只要将其特殊处理即可
求进制的方法一般为辗转相除法(注意:这里求得的数据是反的,需要逆置)
#include<stdio.h>
#include<assert.h>
char* my_itoa(int value,char* buff,unsigned int radix) {
assert(buff!=NULL&&radix>1);//断言buff不为空并且所求进制数大于1
char index[] = "0123456789abcdefghijklmnopqrstuvwxyz";
//定义字符组,用来表示各种需要的数
unsigned int temp = (unsigned int)value;//将有符号的value值强转为无符号型的
int flag = value < 0 && radix == 10 ? 1 : 0;//判断是否为十进制(特殊处理)
if (flag == 1) {//判断为十进制且为负数
buff[0] = '-';//首元素为负号
temp *= -1;//将value变为正数
}
int i = flag;
for (; temp != 0;i++) {
buff[i] = index[temp % radix];
temp /= radix;
}
buff[i] = '\0';
//因为使用辗转相除法求得的是逆序,所以需要将整个数组逆置
for (int j = 0; j < (i - flag)/2;j++) {
int temp = buff[j+flag];
buff[j + flag] = buff[i - 1 - j];
buff[i - 1 - j] = temp;
}
return buff;
}
int main() {
char buff[256];
char* res = my_itoa(11,buff,16);
printf("%s\n",res);
return 0;
}
测试用例:(第一个数字是待转数字,第二个数字是进制数)
边栏推荐
猜你喜欢
Causal learning weekly, issue 10: introduction to the latest causal discovery related papers in iclr2022
On the horizontal trigger and edge trigger of epoll
Kubernetes基础入门
LeetCode103——zigzagLevelOrder of binary tree
Introduction to machine learning: support vector machine-6
LeetCode103——zigzagLevelOrder of binary tree
她力量系列五丨朱海一:以人为本,构建 AI 价值观
CPU affinity
LeetCode912——sort an array—— quick sort algorithm
Rag summary
随机推荐
1091 Acute Stroke (30 分)
她力量系列八丨陈丹琦:我希望女生能够得到更多的机会,男生和女生之间的gap会逐渐不存在的
LeetCode0003——longest substring without repeating characters——Sliding Window
On the horizontal trigger and edge trigger of epoll
LeetCode0022——括号生成——DFS
RAG小结
PAT-2021年冬季考试(满分)
CPU affinity
Leetcode0002——Add Two Numbers——Linked List
MySQL query blob
LeetCode206——反转链表
canny边缘检测
Her power series seven LAN Yanyan: ideal warm 10-year scientific research road, women can be gentle, more confident and professional | women's Day Special
Classic cases of semaphore synchronization and mutual exclusion
Chinese search for introduction to elastic search (8)
Her power series II UCLA Li Jingyi: the last thing women need to do is "doubt themselves"
Leetcode0022 - bracket generation - DFS
She studied in the fourth series of strength, changed her tutor twice in six years, and with a little "stubbornness", Yu Zhou became one of the pioneers of social Chatbot
1087 All Roads Lead to Rome (30 分)
《预训练周刊》第38期: Transformer、BERT结构优化