File: hex2bin.c

package info (click to toggle)
infnoise 0.3.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 27,304 kB
  • sloc: ansic: 2,177; sh: 251; python: 146; makefile: 65
file content (35 lines) | stat: -rw-r--r-- 725 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <ctype.h>

int isHexDigit(int c) {
    return isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}

int readChar(void) {
    int c = getchar();
    while(c != EOF && !isHexDigit(c)) {
        c = getchar();
    }
    return c;
}

int getDigit(char c) {
    c = tolower(c);
    if(c >= 'a' && c <= 'f') {
        return 10 + c - 'a';
    }
    return c - '0';
}

int main() {
    int upper = readChar();
    int lower = readChar();
    while(upper != EOF && lower != EOF) {
        int upperDigit = getDigit(upper);
        int lowerDigit = getDigit(lower);
        putchar((upperDigit << 4) | lowerDigit);
        upper = readChar();
        lower = readChar();
    }
    return 0;
}