A decimal number is categorized as a base 10 numeral due to its span from 0 to 9, encompassing a total of 10 digits within this range. Any sequence of these digits can constitute a decimal number, for instance, 23, 445, 132, 0, 2, and so forth.
Binary Number
A binary number is characterized by its base 2 representation, as it can only consist of the digits 0 and 1. Any sequence of 0s and 1s forms a binary number, for instance, 1001, 101, 11111, 101010, and so forth.
Let's examine some binary representations for decimal numbers.
| Decimal | Binary |
|---|---|
1 |
1 |
2 |
10 |
3 |
11 |
4 |
100 |
5 |
101 |
6 |
110 |
7 |
111 |
8 |
1000 |
9 |
1001 |
10 |
1010 |
Decimal to Binary Conversion Algorithm
- Step 1: Divide the number by 2 through % (modulus operator) and store the remainder in array
- Step 2: Divide the number by 2 through / (division operator)
- Step 3: Repeat the step 2 until number is greater than 0
Let's explore a C code example for converting a decimal number to its binary equivalent.
Example
Example
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10],n,i;
system ("cls");
printf("Enter the number to convert: ");
scanf("%d",&n);
for(i=0;n>0;i++)
{
a[i]=n%2;
n=n/2;
}
printf("\nBinary of Given Number is=");
for(i=i-1;i>=0;i--)
{
printf("%d",a[i]);
}
return 0;
}
Output:
Output
Enter the number to convert: 5
Binary of Given Number is=101