c 语言 将整数 转换为 2 ,8,16 进制数
2015-09-06 22:34
281 查看
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//倒置数组
void revers(char s[])
{
int c, i, j;
j = strlen(s) - 1;//求得s的长度
for(i = 0;i < j;i++ , j--)
{
c = s[i];
s[i] = s[j]; //首尾交换
s[j] = c;
}
}
//将整数 n 以 b 为底的数,并将转换结果以字符串的形式保存在 s 中
// 如:itob(n,s,16) 把整数 n 格式化为 16 进制保存在 s 中
void itob( int n, char s[] , int b)
{
int i, j, sign;
sign = n;
i =0;
if( sign < 0)
{
n = -n;
}
do
{
j = n % b;
s[i++] = (j <= 9) ? j + '0' : j + 'a' -10;
} while ( (n /= b) > 0);
if(sign < 0)
{
s[i++] = '-';
}
s[i] = '\0';
revers(s);
}
int main(void)
{
char buf[500];
int n = 0;
int b = 0;
int t = 0;
printf("输入要转换的数:\n");
while( ( scanf("%d",&n)) != EOF )
{
printf("输入的是: %d\n",n);
printf("输入要转换的进制: 2 ,8,16\n");
scanf("%d",&b);
printf("你输入的:%d,转换为: %d 进制后是: ",n,b);
itob(n,buf,b);
printf("%s\n",buf);
memset(buf,'\0',sizeof(buf));//重置buf 所以元素为 0
b = n = 0; //重置 b n 为零
}
return 0;
}
#include<string.h>
#include<stdlib.h>
//倒置数组
void revers(char s[])
{
int c, i, j;
j = strlen(s) - 1;//求得s的长度
for(i = 0;i < j;i++ , j--)
{
c = s[i];
s[i] = s[j]; //首尾交换
s[j] = c;
}
}
//将整数 n 以 b 为底的数,并将转换结果以字符串的形式保存在 s 中
// 如:itob(n,s,16) 把整数 n 格式化为 16 进制保存在 s 中
void itob( int n, char s[] , int b)
{
int i, j, sign;
sign = n;
i =0;
if( sign < 0)
{
n = -n;
}
do
{
j = n % b;
s[i++] = (j <= 9) ? j + '0' : j + 'a' -10;
} while ( (n /= b) > 0);
if(sign < 0)
{
s[i++] = '-';
}
s[i] = '\0';
revers(s);
}
int main(void)
{
char buf[500];
int n = 0;
int b = 0;
int t = 0;
printf("输入要转换的数:\n");
while( ( scanf("%d",&n)) != EOF )
{
printf("输入的是: %d\n",n);
printf("输入要转换的进制: 2 ,8,16\n");
scanf("%d",&b);
printf("你输入的:%d,转换为: %d 进制后是: ",n,b);
itob(n,buf,b);
printf("%s\n",buf);
memset(buf,'\0',sizeof(buf));//重置buf 所以元素为 0
b = n = 0; //重置 b n 为零
}
return 0;
}
相关文章推荐
- 如何查看ubuntu的内核版本和发行版本号?
- html.ex.day01
- 开发语言的牛人
- c和c++中NULL和0的区别
- 锁·——lock关键字详解
- HDU 5428:The Factor
- 三星Remote Control开发遇到的坑
- 锁·——lock关键字详解
- HDU 5428:The Factor
- hadoop yarn简明教程
- hdfs简要教程
- [网络] TCP三次握手/四次挥手详解
- 绩效管理
- c+-----------------------------抽象类
- Winform设置按钮与窗体背景色一致
- iOS 颜色渐变
- 零基础学python-11.4 语句分隔符
- 零基础学python-11.4 语句分隔符
- 文件查找
- hadoop简要教程