本帖最后由 jackz007 于 2020-3-14 23:00 编辑 #include <stdio.h>
char * bin2oct(char * oct , const char * bin)
{
char c ;
unsigned int d , k , m ;
for(d = 0 , k = 0 ; bin[k] ; d = d * 2 + bin[k] - '0' , k ++) ;
for(m = 0 ; d ; oct[m ++] = '0' + (d % 8) , oct[m] = '\0' , d /= 8) ;
for(k = 0 ; k < m / 2 ; c = oct[k] , oct[k] = oct[m - k - 1] , oct[m - k - 1] = c , k ++) ;
return oct ;
}
char * oct2bin(char * bin , const char * oct)
{
char c ;
unsigned int d , k , m ;
for(d = 0 , k = 0 ; oct[k] ; d = d * 8 + oct[k] - '0' , k ++) ;
for(m = 0 ; d ; bin[m ++] = '0' + (d % 2) , bin[m] = '\0' , d /= 2) ;
for(; m < 32 ; bin[m ++] = '0' , bin[m] = '\0') ;
for(k = 0 ; k < m / 2 ; c = bin[k] , bin[k] = bin[m - k - 1] , bin[m - k - 1] = c , k ++) ;
return bin ;
}
main(void)
{
char c , bin[34] , oct[12] ;
unsigned int k ;
printf("请输入二进制数,输入“#”表示结束:\n") ;
for(k = 0 ; (c = getchar()) != '#' && c != '\n' && k < 32 ; bin[k ++] = c , bin[k] = '\0') {
if(c != '0' && c != '1') {
fprintf(stderr , "输入内容无效!\n") ;
k = 0 ;
break ;
}
}
if(k > 0) {
printf("输入的二进制数:%s\n" , bin) ;
printf("输出的八进制数:%s\n" , bin2oct(oct , bin)) ;
printf("输出的二进制数:%s\n" , oct2bin(bin , oct)) ;
}
}
编译、运行实况:C:\Bin>g++ -o x x.c
C:\Bin>x
请输入二进制数,输入“#”表示结束:
00100000000010100000000010110000#
输入的二进制数:00100000000010100000000010110000
输出的八进制数:4002400260
输出的二进制数:00100000000010100000000010110000
C:\Bin>
|