您的位置:首页 > 其它

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: