Also, don't forget to change your printf to:

printf("The decimal of %d is %ld.", n, stp);

Because your stp is now a long!!

Solved

Posted on 2006-06-04

#include <stdio.h>

#include <conio.h>

#include <math.h>

void main()

{

int i, b = 0, snp[8], t = 7, stp = 0, check, n;

clrscr();

printf("\nInput a binary number : ");

scanf("%d", &n);

for (i = 7; i >= 0 ; i--)

{

if (n - pow(10, i) >= 0)

snp[b] = 1;

else

snp[b] = 0;

//n = n - pow(10, i);

b++;

}

for (i = 0; i < 8 ; i++)

{

if ((snp[i] != 0) && (snp[i] != 1))

{

printf("This is not a binary number.");

getch();

exit();

}

}

for (i = 0; i < 8 ; i++)

{

//printf("%d ", snp[i]);

stp += snp[i] * pow(2, t);

t = t -1;

}

printf("The decimal of %d is %d.", n, stp);

getch();

}

if i change int i, b = 0, snp[8], t = 7, stp = 0, check, n;

to int i, b = 0, check, n;

long int snp[8], t = 7, stp = 0;

it doesn't work

i want input a binary number like 11111111 and then it chane to decimal. How can i do ?

#include <conio.h>

#include <math.h>

void main()

{

int i, b = 0, snp[8], t = 7, stp = 0, check, n;

clrscr();

printf("\nInput a binary number : ");

scanf("%d", &n);

for (i = 7; i >= 0 ; i--)

{

if (n - pow(10, i) >= 0)

snp[b] = 1;

else

snp[b] = 0;

//n = n - pow(10, i);

b++;

}

for (i = 0; i < 8 ; i++)

{

if ((snp[i] != 0) && (snp[i] != 1))

{

printf("This is not a binary number.");

getch();

exit();

}

}

for (i = 0; i < 8 ; i++)

{

//printf("%d ", snp[i]);

stp += snp[i] * pow(2, t);

t = t -1;

}

printf("The decimal of %d is %d.", n, stp);

getch();

}

if i change int i, b = 0, snp[8], t = 7, stp = 0, check, n;

to int i, b = 0, check, n;

long int snp[8], t = 7, stp = 0;

it doesn't work

i want input a binary number like 11111111 and then it chane to decimal. How can i do ?

4 Comments

Also, don't forget to change your printf to:

printf("The decimal of %d is %ld.", n, stp);

Because your stp is now a long!!

Hints:

num << 1 multiplies num by 2

if char ch = '1', then ch - '0' = 1

This would probably be cheating for your homework assignment, but I would just use strtol() with a radix of 2.

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**16** Experts available now in Live!