Home > Article > Backend Development > C program to convert decimal to binary?
Convert an integer from decimal (base-10) to binary (base-2). Assuming the size of the integer is 32 bits, the number needs to be divided by the base. It is used by computers to change integer values into bytes for the computer.
Input:10 Output:1010
If the decimal number is 10
10 divided by 2 the remainder is zero. Therefore, 0.
Divide 10 by 2. The new number is 10/2 = 5.
When divided by 5, the remainder is 1. Hence 1.
Divide 5 by 2. The new number is 5/2 = 2.
When 2 is divided by 2, the remainder is zero. Therefore, 0.
Divide 2 by 2. The new number is 2/2 = 1.
When 1 is divided by 2, the remainder is 1. Therefore, it is 1.
Divide 1 by 2. The new number is 1/2 = 0.
#include <iostream> using namespace std; int main() { long n, d, r, binary = 0; n=10; d = n; int temp = 1; while (n!=0) { r = n%2; n = n / 2; binary = binary + r*temp; temp = temp * 10; } printf("%ld", binary); return 0; }
The above is the detailed content of C program to convert decimal to binary?. For more information, please follow other related articles on the PHP Chinese website!