Showing posts with label binary to decimal. Show all posts
Showing posts with label binary to decimal. Show all posts

Binary to decimal

Another Solution for Binary to Decimal:


SOURCE CODE:


#include stdio(.)h
#include conio(.)h

void showbits(int h)
{
if(h==1)
printf("%d",h);
else
{
showbits(h/2);
printf("%d",h%2);
}
}
main()
{
int num;
void showbits(int h);

printf("BINARY : ");
scanf("%d",&num);
printf("\nBinary of %d equivalent to decimal is ",num);
showbits(num);
getch();
}

Another C Plus Plus

Another Sample Code:


#include
#include
#include

main()
{
int i,n1,t,w,a[100],i1=0;
int n,f2;


printf("[b]PROGRAM FOR DECIMAL TO BINARY CONVERSION[/b]\n");
printf("******************************************\n");
printf("\n\nENTER A NUMBER:");
scanf("%d",&n);
w=n;
f2=w;

if(f2==n)
{
printf("");f2=0;
}
else
{
f2=n-f2;
}
n1=n;

for(i=0;n1>=1;i++)
{
t=n1%2;
n1=n1/2;
i1++;
a[i]=t;
}

printf("\n\nBINARY EQVALENT=>");

for(i=(i1-1);i>=0;i--)
{
printf("%d",a[i]);
}
printf(".");

for(i=1;i<=6;i++)
{
f2=f2*2;
if(f2>=1)
{
printf("1");
f2=f2-1;
}
else
{ printf("0");
}
}
getch();
}

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 %.