编写一个函数itob(int n,char s[],int b),将整数n转换为以b进制的数。保存到s中

简介:

#include <stdio.h>

#include <assert.h>

#include <stdlib.h>

#include <string.h>


void swap(char *p1, char *p2)

{

char tmp = *p1;

*p1 = *p2;

*p2 = tmp;

}


void  reverse(char *pstart, char *pend)

{

assert((pstart != NULL) && (pend != NULL));

while (pstart < pend)

{

swap(pstart, pend);

pstart++;

pend--;

}

}


char *my_itob(int n, char s[], int b)

{

char *p = s;

assert(s != NULL);

if (s != NULL)

{

if (n < 0)

{

*s == '-';

n = n*(-1);

s++;

}

while (n)

{

*s = "0123456789abcdef"[n%b];

n /= b;

s++;

}

*s = '\0';

if (*p == '-')

reverse(p + 1, (p + strlen(p) - 1));

else

reverse(p, (p + strlen(p) - 1));

return p;

}

return NULL;

}



int main()

{

int num = 0;

scanf("%d", &num);

char output[20];

char *p = my_itob(num, output, 2);

printf("%s\n", p);

system("pause");

return 0;

}

1
<br>



本文转自 七十七快 51CTO博客,原文链接:http://blog.51cto.com/10324228/1686488
相关文章
|
3月前
|
存储 Python
语音输入,python数据类型,type()用来查看数据类型,数据类型转换,int(x)转整数,float(x)转换为浮点数,str(x),将对象转为字符串,标识符,标识符不允许使用关键字,关键字参考
语音输入,python数据类型,type()用来查看数据类型,数据类型转换,int(x)转整数,float(x)转换为浮点数,str(x),将对象转为字符串,标识符,标识符不允许使用关键字,关键字参考
|
4月前
详细解读C++char类型函数
详细解读C++char类型函数
36 0
|
5月前
|
存储 C语言
计算 int, float, double 和 char 字节大小
计算 int, float, double 和 char 字节大小。
67 3
|
4月前
|
C语言
C语言-----计算两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
C语言-----计算两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同?
|
5月前
|
存储 Web App开发 编译器
C语言程序设计——int,double,char的用法
C语言程序设计——int,double,char的用法
|
5月前
|
C语言
[C语言][题]两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同。
[C语言][题]两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同。
40 1
|
5月前
|
存储 人工智能 编译器
learn_C_deep_5 (温故知新、sigend char a = -128的深度理解、unsigned int类型的写法规范)
learn_C_deep_5 (温故知新、sigend char a = -128的深度理解、unsigned int类型的写法规范)
|
5月前
|
算法 Java C++
数据结构与算法面试题:实现一个函数 fill(int[] a, int n, int v),使其将大小为 n 的数组 a 填满为 v。
数据结构与算法面试题:实现一个函数 fill(int[] a, int n, int v),使其将大小为 n 的数组 a 填满为 v。
35 0
|
5月前
|
C语言
C语言中通过INT_MAX判断两个非负整数相加是否溢出
C语言中通过INT_MAX判断两个非负整数相加是否溢出
96 0
|
5月前
|
存储
char**传参,获取函数内申请的字符串,外部释放
char**传参,获取函数内申请的字符串,外部释放
74 0