Given a decimal number as input, we need to write a program to convert the given decimal number into equivalent binary number.
Input : 7 Output : 111 Input : 10 Output : 1010 Input: 33 Output: 100001
- Store the remainder when the number is divided by 2 in an array.
- Divide the number by 2
- Repeat the above two steps until the number is greater than zero.
- Print the array in reverse order now.
If the binary number is 10.
Step 1: Remainder when 10 is divided by 2 is zero. Therefore, arr = 0.
Step 2: Divide 10 by 2. New number is 10/2 = 5.
Step 3: Remainder when 5 is divided by 2 is 1. Therefore, arr = 1.
Step 4: Divide 5 by 2. New number is 5/2 = 2.
Step 5: Remainder when 2 is divided by 2 is zero. Therefore, arr = 0.
Step 6: Divide 2 by 2. New number is 2/2 = 1.
Step 7: Remainder when 1 is divided by 2 is 1. Therefore, arr = 1.
Step 8: Divide 1 by 2. New number is 1/2 = 0.
Step 9: Since number becomes = 0. Print the array in reverse order. Therefore the equivalent binary number is 1010.
Below diagram shows an example of converting the decimal number 17 to equivalent binary number.
Below is the implementation of above idea.
We can use bitwise operators to do above job. Note that bitwise operators work faster than arithmetic operators used above.
Thanks to ajay0007 for suggesting above solution.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Program for Binary To Decimal Conversion
- Decimal to binary conversion without using arithmetic operators
- Program for decimal to octal conversion
- Program for decimal to hexadecimal conversion
- Program for octal to decimal conversion
- Decimal to octal conversion with minimum use of arithmetic operators
- Decimal to binary number using recursion
- Convert Binary fraction to Decimal
- Decimal representation of given binary string is divisible by 10 or not
- Convert decimal fraction to binary number
- Binary to decimal and vice-versa in python
- Maximum decimal value path in a binary matrix
- Decimal representation of given binary string is divisible by 5 or not
- Decimal representation of given binary string is divisible by 20 or not
- Queries for decimal values of subarrays of a binary array