当前位置:网站首页>C语言 整数与字符串的相互转换
C语言 整数与字符串的相互转换
2022-07-25 18:00:00 【smile_5me】
之前有整数转字符串得需求,参考了其他大神得博客,这里记录一下,方便后面使用。
char* itoa(int value,char*string,int radix);//value: 要转换的整数,string: 转换后的字符串,radix: 转换进制数,如2,8,10,16 进制等char* itoa(int num,char* str,int radix)
{
char index[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//索引表
unsigned unum;//存放要转换的整数的绝对值,转换的整数可能是负数
int i=0,j,k;//i用来指示设置字符串相应位,转换之后i其实就是字符串的长度;转换后顺序是逆序的,有正负的情况,k用来指示调整顺序的开始位置;j用来指示调整顺序时的交换。
//获取要转换的整数的绝对值
if(radix==10&&num<0)//要转换成十进制数并且是负数
{
unum=(unsigned)-num;//将num的绝对值赋给unum
str[i++]='-';//在字符串最前面设置为'-'号,并且索引加1
}
else unum=(unsigned)num;//若是num为正,直接赋值给unum
//转换部分,注意转换后是逆序的
do
{
str[i++]=index[unum%(unsigned)radix];//取unum的最后一位,并设置为str对应位,指示索引加1
unum/=radix;//unum去掉最后一位
}while(unum);//直至unum为0退出循环
str[i]='\0';//在字符串最后添加'\0'字符,c语言字符串以'\0'结束。
//将顺序调整过来
if(str[0]=='-') k=1;//如果是负数,符号不用调整,从符号后面开始调整
else k=0;//不是负数,全部都要调整
char temp;//临时变量,交换两个值时用到
for(j=k;j<=(i-1)/2;j++)//头尾一一对称交换,i其实就是字符串的长度,索引最大值比长度少1
{
temp=str[j];//头部赋值给临时变量
str[j]=str[i-1+k-j];//尾部赋值给头部
str[i-1+k-j]=temp;//将临时变量的值(其实就是之前的头部值)赋给尾部
}
return str;//返回转换后的字符串
}int main(void)
{
int index = 100;
unsigned char num[10];
itoa(index,num,10);
printf("%s\n",num);
return 0;
}边栏推荐
- 带你初步了解多方安全计算(MPC)
- Brief introduction to clustered index, secondary index, index push down
- Mongodb cluster and sharding
- Redis source code and design analysis -- 15. RDB persistence mechanism
- 11. Camera and lens
- Redis source code and design analysis -- 16. AOF persistence mechanism
- HCIP第一天实验
- Notes on Flickr's dataset
- 「数字安全」警惕 NFT的七大骗局
- Installation and operation instructions of SVN client (TortoiseSVN)
猜你喜欢

「行话」| 用DevOps高效交付游戏,是种什么体验?

2022/7/23

绘制pdf表格 (二) 通过itext实现在pdf中绘制excel表格样式设置中文字体、水印、logo、页眉、页码

食品安全 | 八问八答带你重新认识小龙虾!这样吃才对!

什么是 IP SSL 证书,如何申请?

What scenarios have rust, which is becoming more and more mature, applied?

Hcip first day experiment

TME2022校园招聘后台开发/运营开发/业务运维/应用开发笔试(I)编程题的一点自我分析

ORB_SLAM3复现——上篇

Redis源码与设计剖析 -- 16.AOF持久化机制
随机推荐
Redis source code and design analysis -- 16. AOF persistence mechanism
如何判断静态代码质量分析工具的性能?这五大因素必须考虑
I'm also drunk. Eureka delayed registration and this pit!
Trooper
OSPF comprehensive experiment
更新|3DCAT实时云渲染 v2.1.2版本全新发布
Oracle导入出错:IMP-00038: 无法转换为环境字符集句柄
云流化和云桌面有什么关系
Redis source code and design analysis -- 17. Redis event processing
SLA 、SLO & SLI
SVN客户端(TortoiseSVN)安装及使用说明
Postman get started quickly
Li Kai: the interesting and cutting-edge audio and video industry has always attracted me
2022/7/23
Joseph Ring problem
Installation and operation instructions of SVN client (TortoiseSVN)
Redis源码与设计剖析 -- 17.Redis事件处理
Redistemplate solves the problem of oversold inventory in the seckill system with high speed - redis transaction + optimistic lock mechanism
go接口变量的类型断言
NPDP多少分通过?如何高分通过?