recursion - C Converting 4 digit numbers to binary -
i want print binary equivalent of numbers file in 20 bit field spaces after every 4 bits when number exceeds 1024 (i've tested this), no longer outputs in binary in base don't know (i.e. 1234 = 0000 0014 1006 5408)
here code
#include <stdio.h> long converttobinary(long); int main() { char binnum[20]; //binary number char array int i; long b, decnum; //b output binary number, decnum each input number file file *fileptr; fileptr = fopen("numbers.txt", "r"); while (!feof(fileptr)) { fscanf(fileptr, "%li", &decnum); if (decnum < 0 || decnum > 65535) { printf("error, %5li out of range.\n", decnum); continue; } b = converttobinary(decnum); //function call binary conversion = 18; while (i >= 0) { if (i == 4 || == 9 || == 14) { binnum[i] = ' '; } else if (b != 0) { binnum[i] = b % 10 + '0'; b /= 10; } else { binnum[i] = '0'; } i--; } binnum[19] = '.'; printf("the binary representation of %5li is: ", decnum); (i = 0; i<20; i++) { printf("%c", binnum[i]); } printf("\n"); } return 0; } //recursion function long converttobinary(long number) { if (number == 0) { return 0; } else { return (number % 2 + 10 * converttobinary(number / 2)); } }
the file numbers.txt
has numbers : 0 1 2 3 16 17 1234 5678 65535
your converttobinary
function producing decimal-coded-binary (as opposed binary-coded-decimal) uses decimal digit per bit.
it looks long
has same range int
on system, i.e. 231, covers ten decimal digits. once eleventh digit, overflow.
switching unsigned long long
, has 64 bits, fix problem. however, sub-optimal: better off writing to-binary conversion writes zeros , ones array of char
s provide. can recursively if you'd like, iterative solution fine.
note to-binary conversion not need insert spaces char
array. can done main
function.
Comments
Post a Comment