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
#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