Reading/Parsing Command-Line Arguments in C; binary and decimal conversions -
i have write program in c reads , parses different command-line arguments have no idea start. have write usage:
usage: binary option size number option: -b number binary , output in decimal. -d number decimal , output in binary. size: -8 input unsigned 8-bit integer. -16 input unsigned 16-bit integer. -32 input unsigned 32-bit integer. -64 input unsigned 64-bit integer. number: number converted.
other this, not sure how user input , go conversions. great!
you can take following code-snippet , work on there, please note:
i not see need make use of
size
argument. if argument essential exercise (or other reason behind question), you'll need think how want use it.i not perform assertion on input number, code below assumes legal decimal input number when
option = -d
, legal binary input number whenoption = -d
.there more 1 way implement it, , code below merely example.
#include <stdio.h> #include <string.h> unsigned long long str_to_ull(char* str,int base) { int i; unsigned long long ull = 0; (i=0; str[i] != 0; i++) { ull *= base; ull += str[i]-'0'; } return ull; } void print_ull(unsigned long long ull,int base) { if (ull/base > 0) print_ull(ull/base,base); printf("%d",ull%base); } int main(int argc,char* argv[]) { char* option; char* size ; char* number; unsigned long long number = 0; if (argc < 4) { printf("missing input arguments\n"); return -1; } option = argv[1]; size = argv[2]; number = argv[3]; if (strcmp(option,"-b") == 0) { number = str_to_ull(number,2); print_ull(number,10); return 0; } if (strcmp(option,"-d") == 0) { number = str_to_ull(number,10); print_ull(number,2); return 0; } printf("invalid input arguments\n"); return -1; }
Comments
Post a Comment