-
binary to decimal
Hey,
I can change decimal numbers to binary but I am having trouble doing it other way around...
Code:
int main()
{
int number, remainder;
int highBitValue, numBits, bit;
int i;
printf("Please enter a decimal number: ");
scanf("%d", &number);
fflush(stdin);
printf("The equivalent representation of %d in binary is ", number);
/* find the largest power of 2 that fits into number */
highBitValue = 1; numBits = 0;
remainder = number;
while (remainder != 0)
{
remainder = remainder / 2;
/* we keep track of both the highest digit value and the number of digits */
highBitValue = highBitValue * 2;
numBits++;
}
remainder = number;
/* avoid leading 0 bit */
highBitValue = highBitValue / 2;
for (i=0; i<numBits; i++)
{
/* find the highest bit in remainder */
bit = remainder / highBitValue;
printf("%d", bit);
/* get ready for the next bit */
remainder = remainder - bit * highBitValue;
highBitValue = highBitValue / 2;
}
Thank you.
-
fflush(stdin) is undefined - see FAQ
bit manipulations better to do using bit-oparations like | ~ & >> <<
show your attempt to convert binary to decimal and we will help to fix errors...
or search form for samples - there are a lot (twice per month at least this question is discussed)
-
hi, I finished writing the code but it seems I am trying to hard.. I am trying it to make it less complicated but this is what I got so far,
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n,i,temp1,temp2,temp3,temp4,temp5,remainder,j,k,p,count,count2,a;
double bits;
bits = pow(2,n);
printf("Please enter an integer between 1 and 33:");
scanf("%d",&n);
bits = pow(2,n);
printf("\nNumber n of bits in the integers: %d\n",n);
printf("Number of integers with n=4 bits: %d\n",bits);
printf("\n\nAll integers with 0 bits equal to 1 listed in ascending order:\n");
i = 1;
temp1 = n;
temp2 = n;
printf("0\t");
while (temp1 != 0)
{
printf("0");
temp1--;
}
printf("\n\n");
int l;
for(l=1;l<=n;l++)
{
printf("All integers with %d bits equal to 1 listed in ascending order:\n",l);
i=1;
while(i != bits)
{
int temp3 = i;
int temp4 = i;
int count = 0;
while(temp3 != 0)
{
temp3 = temp3 / 2;
count++;
}
int k = count - 1;
int sum = 0;
int count3 = 0;
while (count != 0)
{
int power1 = (int) pow(2,k);
double power2 = pow(10, k);
int a = temp4 / power1;
temp4 = temp4 % power1;
sum = sum + a * power2;
if(a == 1)
{
count3++;
}
k--;
count --;
}
int need1 = sum;
if (count3 == l)
{
int f;
printf("%d\t",i);
count2=0;
while (need1 != 0)
{
need1 = need1 / 10;
count2++;
}
f = n - count2;
while(f != 0)
{
printf("0");
f--;
}
printf("%d\n",sum);
}
i++;
}
printf("\n");
}
system("pause");
}
can you help me make this more understandable for other people to understand without having to trace its every move =S