Sunday, April 25, 2021

Convert hex to binary faster than xxd part 2/2

   static int hexdigit(char x)
   {
     if (x >= '0' && x <= '9') return x - '0';
     if (x >= 'a' && x <= 'f') return 10 + (x - 'a');
     if (x >= 'A' && x <= 'F') return 10 + (x - 'A');
     return -1;
   }
   int hexparse(unsigned char *y,long long len,const char *x)
   {
     if (!x) return 0;
     while (len > 0) {
       int digit0;
       int digit1;
       digit0 = hexdigit(x[0]); if (digit0 == -1) return 0;
       digit1 = hexdigit(x[1]); if (digit1 == -1) return 0;
       *y++ = digit1 + 16 * digit0;
       --len;
       x += 2;
     }
     if (x[0]) return 0;
     return 1;
   }
   #define BLOCK 4096
   static unsigned char buf[BLOCK + 1];
   int main(int argc, char **argv) {
       long long r,w;
       for (;;) {
           r = readblock(0, buf, BLOCK);
           if (r == -1) _exit(0);
           for (;;) {
               if (r <= 0) goto end;
               if (buf[r - 1] == '\n') { --r; continue; }
               if (buf[r - 1] == '\r') { --r; continue; }
               break;
           }
           buf[r] = 0;
           if (r % 2) _exit(0);
           w = r / 2;
           if (!hexparse(buf, w, (char *)buf)) break;
           if (writeall(1, buf, w) == -1) break;
           if (r != BLOCK) break;
       }
   end:
       if (fsyncfd(1) == -1) _exit(0);
       _exit(0);
   }

Comments URL: https://news.ycombinator.com/item?id=26937730

Points: 1

# Comments: 0



from Hacker News: Newest https://ift.tt/3aDtejr
via IFTTT

No comments:

Post a Comment

Six athletes to compete under Russian flag at Paralympics

Six Russian and four Belarusian athletes will compete under their nations' flags at the upcoming Winter Paralympics. from BBC News htt...