How to convert decimal to binary: Keep dividing the decimal number by 2 until the quotient is zero, and then write the remainder from bottom to top; the conversion code "int main(void){int n,len ;int a[20];scanf("%d",&n);while(n/2){a[len ]=n%2;n=n/2;}a[len ]=n%2;for (i=len-1;i>=0;i--){printf("%d",a[i]);}}".
The operating environment of this tutorial: windows7 system, c99 version, Dell G3 computer.
C language decimal to binary conversion
In C language, converting decimal to other bases is more complicated.
The decimal integer is converted into an N-based integer using the method of "divide by N, take remainder, and arrange in reverse order". The specific method is:
Use N as the divisor and divide the decimal integer by N to get a quotient and remainder;
Keep the remainder. If you continue to divide the quotient by N, you will get a new quotient and remainder;
Still retain the remainder, if you continue to divide the quotient by N, you will get a new quotient and remainder;
......
Repeat this process, retaining the remainder each time, and divide by N until the quotient is 0.
Take the remainder obtained first as the low-order digit of the N-base number, and the remainder obtained later as the high-order digit of the N-base number. Arrange them in order to get the N-base number. .
And If you want to convert decimal to binary, you need to use the principle of "divide by 2, take the remainder, and arrange in reverse order":
Constantly convert the number Divide by 2 until the quotient is zero, and then write the remainder from bottom to top to get the binary representation of the number.
The following figure demonstrates the process of converting the decimal number 42 into binary:
It is known from the figure that the decimal number 42 The result converted to binary is 101010.
Implementation code:
#include <stdio.h> int main(void) { int n,length; //length用来装二进制数的个数 int a[20]; //定义一个数组来装余2得到的余数 scanf("%d",&n); //输入十进制的数字 while(n/2){ //当n=1时,n/2=0,此时while(0)不执行while中的语句,直接执行下面的语句 a[length++] = n%2; //将除2得到的余数装入数组中 n = n/2; //除二 } a[length++] = n%2; //存储最后一个余数 //将余数从下往上输出 for(int i = length-1;i>=0;i--) printf("%d",a[i]); }
Related recommendations: "C Video Tutorial"
The above is the detailed content of How to convert decimal to binary in c language. For more information, please follow other related articles on the PHP Chinese website!