示例:十进制转二进制
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//提供CHAR_BIT的定义,CHAR_BIT表示每字节的位数
#include <limits.h>
char * itobs(int, char *);
void show_bstr(const char *);
int main(int argc, char* argv[])
{
char bin_str[CHAR_BIT * sizeof(int) + 1];
int number;
puts("Enter integers and see them in binary.");
puts("Non-numeric input terminates program.");
while (scanf("%d", &number) == 1)
{
itobs(number, bin_str);
printf("%d is", number);
show_bstr(bin_str);
putchar('\n');
}
puts("Bye!");
system("pause");
return 0;
}
char * itobs(int n, char * ps)
{
int i;
const static int size = CHAR_BIT * sizeof(int);
for (i = size - 1; i >= 0; i--, n >>= 1)
//01代表八进制1
ps[i] = (01 & n) + '0';//1 + '0' 表示 '1'
ps[size] = '\0';
return ps;
}
void show_bstr(const char * str)
{
int i = 0;
while (str[i]) /* 不是一个空字符 */
{
putchar(str[i]);
if (++i % 4 == 0 && str[i])
putchar(' ');
}
}
运行测试