|
| 1 | +// |
| 2 | +// See for more details: |
| 3 | +// https://github.com/abranhe/binary.c |
| 4 | +// |
| 5 | +// cli.c |
| 6 | +// |
| 7 | +// MIT licensed. |
| 8 | +// Copyright (c) Abraham Hernandez <[email protected]> |
| 9 | +// |
| 10 | + |
| 11 | +#include <stdio.h> |
| 12 | +#include <string.h> |
| 13 | +#include <stdlib.h> |
| 14 | +#include "binary.h" |
| 15 | + |
| 16 | +const char |
| 17 | +*show_help() { |
| 18 | + return "\n\ |
| 19 | + An small library to work with binary numbers\n\n\ |
| 20 | + Usage:\n\n\ |
| 21 | + $ binary <option> <input> \n\n\ |
| 22 | + Options:\n\n\ |
| 23 | + -is, --is-binary check if a number is binary\n\ |
| 24 | + --to-decimal convert a binary number to decimal\n\ |
| 25 | + --to-binary convert a decimal number to binary\n\ |
| 26 | + -v, --version output version number\n\ |
| 27 | + -h, --help output usage information\n\n\ |
| 28 | + Example:\n\n\ |
| 29 | + $ binary --is-binary 10101000\n\ |
| 30 | + true\n\ |
| 31 | + $ binary --to-decimal 1011\n\ |
| 32 | + 7\n\n"; |
| 33 | +} |
| 34 | + |
| 35 | +/* CLI. */ |
| 36 | +int |
| 37 | +main(int argc, char **argv) { |
| 38 | + char *a = argv[1]; |
| 39 | + char *b = argv[2]; |
| 40 | + |
| 41 | + if (argc == 2) { |
| 42 | + if (!strcmp(a, "-v") || !strcmp(a, "--version")) { |
| 43 | + printf("%s", "1.0.0\n"); |
| 44 | + return 0; |
| 45 | + } |
| 46 | + |
| 47 | + if (!strcmp(a, "-h") || !strcmp(a, "--help")) { |
| 48 | + printf("%s", show_help()); |
| 49 | + return 0; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + if (argc == 3) { |
| 54 | + if (!strcmp(a, "-is") || !strcmp(a, "--is-binary")) { |
| 55 | + char *pb; |
| 56 | + is_binary(strtoll(b, &pb, 0)) |
| 57 | + ? printf("binary\n") |
| 58 | + : printf("non-binary\n"); |
| 59 | + return 0; |
| 60 | + } |
| 61 | + |
| 62 | + if (!strcmp(a, "--to-decimal")) { |
| 63 | + char *pb; |
| 64 | + printf("%ld\n", to_decimal(strtoll(b, &pb, 0))); |
| 65 | + return 0; |
| 66 | + } |
| 67 | + |
| 68 | + if (!strcmp(a, "--to-binary")) { |
| 69 | + char *pb; |
| 70 | + printf("%lld\n", to_binary(strtol(b, &pb, 0))); |
| 71 | + return 0; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + if (argc != 3) { |
| 76 | + fprintf(stderr, "\033[31mBinary expects two arguments.\n\033[0m\n"); |
| 77 | + fprintf(stderr, "\033[31mSee `--help` for more details.\033[0m\n"); |
| 78 | + return 1; |
| 79 | + } |
| 80 | + return 0; |
| 81 | +} |
0 commit comments