Advertisement
STANAANDREY

hex2text

Nov 21st, 2022
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <assert.h>
  5. #define NMAX 101
  6.  
  7. char *hex2text(const char *const hex) {
  8.   const int n = strlen(hex) - 1;
  9.   assert(n % 2 == 0);
  10.   char *text = malloc(sizeof(char) * (n / 2 + 1));
  11.   if (text == NULL) {
  12.     return NULL;
  13.   }
  14.   text[0] = 0;
  15.   for (int i = 0; i < n; i += 2) {
  16.     char aux[3];
  17.     strncpy(aux, hex + i, 2);
  18.     text[i / 2] = strtol(aux, NULL, 16);
  19.   }
  20.   text[n / 2 + 1] = 0;
  21.   return text;
  22. }
  23.  
  24. int main() {
  25.   char hex[NMAX], *text;
  26.   if (fgets(hex, NMAX, stdin) != NULL) {
  27.     text = hex2text(hex);
  28.     if (text != NULL) {
  29.       puts(text);
  30.       return 0;
  31.     }
  32.   }
  33.   puts("Error!");
  34.   return 0;
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement