# Thread: Decimal to binary conversion

1. ## Decimal to binary conversion

Ive been trying for days to figure out how to do decimal to binary conversion... ive been trying to modules the number by 2 to get the remainder but my proble is saving the remainders in the right order to be printed... the asignment is as follows, print a table of the binary octal and hexadecimal equivalents from 1 to 256. ive got the octal and hexidecimal down... this is basic C programming.. im only in my 7th week of learning it, can someone please help?? here is the code i have already
Code:
```#include <stdio.h>

int main()
{

int x;

for( x = 1; x <= 256; x++ ) {

printf( "%d", x );
printf( "\t" );
printf( "%o", x );
printf( "\t" );
printf( "%x", x );
printf( "\n" );
}

return 0;
}```
Antoni

2. hope this bit helps in your case

Code:
```#include<stdio.h>

int main()
{
int num,i=0;
int binary[10]={0};

scanf("%d",&num);
printf("Binary value of %d is ",num);
while(num!=0)
{

binary[i++]=num%2;
num/=2;
}

for(;i>=0;i--)
printf("%d",binary[i]);

getchar();
}```
this code calculates the binary value of the decimal value entered by the user

s.s.harish

3. You could do this too,

Code:
```#include <stdio.h>

int main()
{
int x, i;
for(x =1; x <= 256; x++)
{
printf( "%d\t", x );
printf( "%o\t", x );
printf( "%x\t", x );

for(i = 0; i < 33; i++)
{
x = x >> 1;
}
printf("\n");
}
return 0;
}```
Its bitwise operators which is not basic so if you do not want to use it thats ok.

4. Originally Posted by Dave_Sinkula
>You could do this too

I don't suppose you tried this code first?
Oh boy I am sorry, definately should have done that. I fixed it here.

Code:
```#include <stdio.h>

int main()
{
int x, t, i;
for(x =1; x <= 256; x++)
{
printf( "%d\t", x );
printf( "%o\t", x );
printf( "%x\t", x );
t = x;
for(i = 0; i < 33; i++)
{
t = t << 1;
}
printf("\n");
}
return 0;
}```
Edited: Realized it in class it's not a good day.

5. Stumpster123: The way you print out the binary is still wrong since it goes in the wrong direction. So 2 is meant to be 0000 0010 but your code will print it as 0100 0000. A simple fix to this is to place the values into an array and print out the array in the reverse order once you have all the bits down.

6. A simpler way is to start with the high bit and work down to the low bit.

Quzah.