current position:Home>Decimal to binary, really do not know how to achieve multiple number conversion and output, C language

Decimal to binary, really do not know how to achieve multiple number conversion and output, C language

2022-02-03 01:59:41 CSDN Q & A

Write a function , Its parameter is an integer N, The return value is also an integer ( The assumption is R), Rules are integers R Write out ( The output from ) yes N In binary form . for example : Parameter is 15, The return value should be 1111. Enter several groups of integers in the main function , Output its binary form in turn .

sample input :
15 16 17 63 64 65
No blank lines at the end
sample output :
1111
10000
10001
111111
1000000
1000001
No blank lines at the end
sample input :
0 1 123 456 789
No blank lines at the end




Refer to the answer 1:
#include <stdio.h>int f(int n) {    int r = 0;    int b = 1;    while(n) {        r += (n % 2) * b;        n /= 2;        b *= 10;    }    return r;}int main(){    int n;    while (scanf("%d", &n) == 1)        printf("%d\n", f(n));    return 0;}



Refer to the answer 2:



Refer to the answer 3:

A simple implementation :

#include <stdio.h>void OctToBinary(int num,char * str){    int i,j,k=0;    int zero = 0;    for(i=31;i>=0;i--){        j = (num>>i)&1;        if(zero==0&&j==1){  // Until the first bit of the integer is 1 The binary of is , Start reading string array              zero=1;            str[k]='1';            //printf("i=%d,j=%d,str[%d]=%c\n",i,j,k,str[k]);            k++;                    }        if(zero==1){   // Read integer binary as 1 The rest of the following bits              str[k] = '0'+j;            //printf("i=%d,j=%d,str[%d]=%c\n",i,j,k,str[k]);            k++;        }            }    }int main(void){        int num;    char str[32]={0};  // Initializes an array of characters      int i=0;    while(i<5){        scanf("%d",&num);        OctToBinary(num,str);        printf("%d to binary : %s\n",num,str);    }        return 0;    }



Refer to the answer 4:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202030159391545.html

Random recommended