Загрузка данных


#include <stdio.h>

int is_hex_digit(char symbol);
int hex_to_number(char symbol);
char number_to_hex(int number);
int encode_mode(void);
int decode_mode(void);

int main(int argc, char **argv) {
    int result = 0;

    if (argc == 2 && argv[1][0] == '0' && argv[1][1] == '\0') {
        result = encode_mode();
    } else if (argc == 2 && argv[1][0] == '1' && argv[1][1] == '\0') {
        result = decode_mode();
    }

    if (!result) {
        printf("n/a");
    }

    return 0;
}

int is_hex_digit(char symbol) {
    return (symbol >= '0' && symbol <= '9') ||
           (symbol >= 'A' && symbol <= 'F') ||
           (symbol >= 'a' && symbol <= 'f');
}

int hex_to_number(char symbol) {
    int number = 0;

    if (symbol >= '0' && symbol <= '9') {
        number = symbol - '0';
    } else if (symbol >= 'A' && symbol <= 'F') {
        number = symbol - 'A' + 10;
    } else if (symbol >= 'a' && symbol <= 'f') {
        number = symbol - 'a' + 10;
    }

    return number;
}

char number_to_hex(int number) {
    char symbol;

    if (number < 10) {
        symbol = number + '0';
    } else {
        symbol = number - 10 + 'A';
    }

    return symbol;
}

int encode_mode(void) {
    char symbol;
    char separator;
    int first_output = 1;
    int result = 1;
    int scan_result;

    scan_result = scanf("%c%c", &symbol, &separator);

    while (result && scan_result == 2) {
        if (separator != ' ' && separator != '\n') {
            result = 0;
        } else {
            int value = symbol;

            if (!first_output) {
                printf(" ");
            }

            printf("%c%c", number_to_hex(value / 16), number_to_hex(value % 16));
            first_output = 0;

            if (separator == '\n') {
                scan_result = EOF;
            } else {
                scan_result = scanf("%c%c", &symbol, &separator);
            }
        }
    }

    if (scan_result != EOF) {
        result = 0;
    }

    return result;
}

int decode_mode(void) {
    char first;
    char second;
    char separator;
    int first_output = 1;
    int result = 1;
    int scan_result;

    scan_result = scanf("%c%c%c", &first, &second, &separator);

    while (result && scan_result == 3) {
        if (!is_hex_digit(first) || !is_hex_digit(second) ||
            (separator != ' ' && separator != '\n')) {
            result = 0;
        } else {
            int value = hex_to_number(first) * 16 + hex_to_number(second);

            if (!first_output) {
                printf(" ");
            }

            printf("%c", value);
            first_output = 0;

            if (separator == '\n') {
                scan_result = EOF;
            } else {
                scan_result = scanf("%c%c%c", &first, &second, &separator);
            }
        }
    }

    if (scan_result != EOF) {
        result = 0;
    }

    return result;
}