I'm trying to convert some text (character by character) to its binary representation. For some reason the print statement printf("Hold is %d or %c: ", hold, hold);
is changing the output of my function and I have no idea how to explain it. Any help would be greatly appreciated. The test file is just a text file with Hello, World!
inside of it.
With it:
Hold is 72 or H: 01001000
Hold is 101 or e: 01100101
Hold is 108 or l: 01101100
Hold is 108 or l: 01101100
Hold is 111 or o: 01101111
Hold is 44 or ,: 00101100
Hold is 32 or : 00100000
Hold is 87 or W: 01010111
Hold is 111 or o: 01101111
Hold is 114 or r: 01110010
Hold is 108 or l: 01101100
Hold is 100 or d: 01100100
Hold is 33 or !: 00100001
Without it:
1000 �
0101 �
1100 �
1100 �
1111 �
1100 �
0000 �
0111 �
1111 �
0010 �
1100 �
0100 �
0001 �
Code
#include <stdio.h>
#include <string.h>
void decimal_to_binary(unsigned long num, FILE *out) {
int i = 255, a = 0;
char binarr[255];
for (i = 0; i < 255; i++) { binarr[i] = '0'; }
if (num != 0) {
while (num != 0) {
if (num % 2 == 0) {
binarr[i] = '0';
i--;
} else {
binarr[i] = '1';
i--;
}
num /= 2;
}
} else {
fprintf(out, "00000000");
}
fprintf(out, "%s ", binarr + strlen(binarr) - 8);
printf("%s\n", binarr + strlen(binarr) - 8);
memset(binarr, 0, sizeof(binarr));
}
int main(int argc, char *argv[]) {
int hold;
FILE *in = fopen(argv[1], "r");
FILE *out = fopen(argv[2], "w+");
while (!feof(in)) {
hold = fgetc(in);
if (hold > 0 && hold != 10){
printf("Hold is %d or %c: ", hold, hold);
decimal_to_binary(hold, out);
}
}
fclose(in);
fclose(out);
return 0;
}