Binary To Decimal

Computers work on the principle of number manipulation. Inside the computer, the numbers are represented in bits and bytes. For example, the number three is represented by a byte with bits 0 & 1 set; 00000011. This is numbering system using base 2. People commonly use a decimal or Base 10 numbering system. What this means is that in Base 10, count from 0 to 9 before adding another digit. The number 22 in Base 10 means we have 2 sets of 10's and 2 sets of 1's.

Base 2 is also known as binary since there can only be two values for a specific digit; either a 0 = OFF or a 1 = ON. You cannot have a number represented as 22 in binary notation. The decimal number 22 is represented in binary as 00010110 which by following the below chart breaks down to:

Bit Position
7
6
5
4
3
2
1
0

1 1 1 1 1 1 1 1
Decimal 128 64 32 16 8 4 2 1

22 or 00010110:

All numbers representing 0 are not counted, 128, 64, 32, 8, 1 because 0 represents OFF

However, numbers representing 1 are counted, 16 + 4 + 2 = 22 because 1 represents ON

Decimal Values and Binary Equivalents chart:

DECIMAL
BINARY
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010
16 10000
32 100000
64 1000000
100 1100100
256 100000000
512 1000000000
1000 1111110100
1024 10000000000



SOURCE CODE:

#include iostream
#include conio (.) h
using namespace::std;

void binary(int decimal) {
int remainder;

if(decimal <= 1) { cout << remainder =" decimal%2;">> 1);
cout <<>> num;
cout << endl << "Binary of " << num << " is ";
binary(num);

getch();
}





Example output:

Enter decimal: 39

Binary of 39 is 100111



HINT:

This just keeps right shifting ( >> ) the number by one bit and printing the binary value of the last bit which is derived using %.

0 comments:

Post a Comment