# Converting decimal to binary within a I/O program

• 11-25-2006
RandomX
Converting decimal to binary within a I/O program
I have to make a 'C' program that takes a set of decimal numbers that are stored in an input file, and then convert the decimal numbers to binary, and then store those conversions into the output file.

I have the program done that reads the input file and stores it in the output file, but I dont know what I need to add in order to convert the decimal numbers.

Here is what I have:

Code:

```#include<stdio.h> #include<string.h> int main() {         FILE *input,*output;         char littleman[8];         int k;         input = fopen("LMC.s","r");         output = fopen("LMC.o","w");         while(fscanf(input, "%s%s",opcode,address)!=EOF)                 {                 fprintf(output,"Opcode: %s \t\tAddress: %s\n",opcode,address);                 }         fclose(output);         fclose(input);         return 0; }```
any help would be great. thanks
• 11-26-2006
Happy_Reaper
Here, look at this.

Look up decimal to binary conversion. Translate that into code. And search the forums. I'm quite positive this thread has been brought up more than enough times...
• 11-26-2006
nacho4d
try with shift!
lets suppose that you have the number you want to convert to binary in a int decNum .
Then the only thing what you have to do is to shift that number one bit to the left

for example you have 13 (which is 0000 ... 0000 1101) you shift it to the left once and then with a if check if is positive or negative. if is negative print out a 0 if not print out a 1 ... and so on ... (the lenght of a integer is 32 bits , so, you have to repeat this 32 times, until the 13 has been shifted 32 times to the left.)

Continuing with my example...., suppose that you have shifted the 13 27-times...,already (only 5 times left) so, your variable decNum does not contain 13 already... actually contains 0110 1000 0000 ... 0000.

In the next iteration the 0110 1000 0000... 0000 will become 1101 0000 0000... 0000 and for the first time it will become a negative number, so according to your if condition you will have a 1 printed out.
Next iteration ... the same. (you get a 1)
Next iteration ... you will have again a positive number..., so you will get a 0
and the next iteration ... you get a 1
and there you have your 32 iterations... so. your cycle is over...
and you have. 27 ceros... a 1 another 1 one 0 and a 1 ... wichh is the binary for 13

With this I think you can do it...

PD I am not 100 % percent sure of the lenght of int... it depends on the machine... you better use sizeof(int).
• 11-26-2006
nacho4d
You can use this... maybe...
Code:

```void print_bitposition(int w) {   int i;   for (i=0;i<32;i++){       if (w<0) printf("1");       else printf("0");       w=w<<1; }```
• 11-26-2006
maxorator
Code:

`w=w<<1;`
It can be just done like this:
Code:

`w<<=1;`