Advertisement
STANAANDREY

text2hex

Dec 24th, 2022
982
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. char *text2hex(const char *const string) {
  6.   const int n = strlen(string);
  7.   char *hex = malloc(sizeof(char) * (n * 2 + 1));
  8.   if (hex == NULL) {
  9.     fprintf(stderr, "failed to alloc!\n");
  10.     exit(EXIT_FAILURE);
  11.   }
  12.   hex[0] = 0;
  13.   for (int i = 0; i < n; i++) {
  14.     char aux[2] = {};
  15.     sprintf(aux, "%x", (int)string[i]);
  16.     strcat(hex, aux);
  17.   }
  18.   return hex;
  19. }
  20.  
  21. int main(void) {
  22.   char s[] = "abc", *res = NULL;
  23.   res = text2hex(s);
  24.   puts(res);
  25.   free(res);
  26.   return 0;
  27. }
  28.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement