tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

hex.c (1347B)


      1 #include <unistd.h>
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 
      5 int
      6 tohex(int c)
      7 {
      8    if ((c >= '0') && (c <= '9')) {
      9        return c - '0';
     10    }
     11    if ((c >= 'a') && (c <= 'f')) {
     12        return c - 'a' + 10;
     13    }
     14    if ((c >= 'A') && (c <= 'F')) {
     15        return c - 'A' + 10;
     16    }
     17    return 0;
     18 }
     19 
     20 int
     21 isspace(int c)
     22 {
     23    if (c <= ' ')
     24        return 1;
     25    if (c == '\n')
     26        return 1;
     27    if (c == '\t')
     28        return 1;
     29    if (c == ':')
     30        return 1;
     31    if (c == ';')
     32        return 1;
     33    if (c == ',')
     34        return 1;
     35    return 0;
     36 }
     37 
     38 void
     39 verify_nibble(int nibble, int current)
     40 {
     41    if (nibble != 0) {
     42        fprintf(stderr, "count mismatch %d (nibbles=0x%x)\n", nibble, current);
     43        fflush(stderr);
     44    }
     45 }
     46 
     47 int
     48 main(int argc, char **argv)
     49 {
     50    int c;
     51    int current = 0;
     52    int nibble = 0;
     53    int skip = 0;
     54 
     55    if (argv[1]) {
     56        skip = atoi(argv[1]);
     57    }
     58 
     59 #define NIBBLE_COUNT 2
     60    while ((c = getchar()) != EOF) {
     61        if (isspace(c)) {
     62            verify_nibble(nibble, current);
     63            continue;
     64        }
     65        if (skip) {
     66            skip--;
     67            continue;
     68        }
     69        current = current << 4 | tohex(c);
     70        nibble++;
     71        if (nibble == NIBBLE_COUNT) {
     72            putchar(current);
     73            nibble = 0;
     74            current = 0;
     75        }
     76    }
     77    return 0;
     78 }