Home > Backend Development > C++ > body text

C program to convert decimal to binary?

WBOY
Release: 2023-09-08 17:45:08
forward
1171 people have browsed it

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
Copy after login

Explanation

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.

  • < p>number becomes = 0. Print an array in reverse order. The equivalent binary number is 1010.

Example

#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;
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template