/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <string.h>

char tohex(int val)
{
   return (val < 10) ? ('0' + val) : ('A' + val - 10);
}

int fromhex(char c)
{
   return (c < 'A') ? (c - '0') : (c - 'A' + 10);
}

void bin2hex(char *s1, int n1, char *s2)
{
   int i;
   int ix = 0;
   for(i=0;i<n1;i++)
   {
      s2[ix] = tohex((s1[i] >> 4) & 0x0F);
      ix++;
      s2[ix] = tohex(s1[i] & 0x0F);
      ix++;
   }
   s2[ix] = '\0';
}

void hex2bin(char *s1, char *s2, int *n2)
{
   int i;
   for(i=0;i<strlen(s1)/2;i++)
   {
      s2[i] = (fromhex(s1[2*i]) << 4) | fromhex(s1[2*i+1]);
   }
   *n2 = strlen(s1)/2;
}

int main()
{
   int l;
   char s1[10] = "ABC";
   char s2[10];
   char s3[10];
   bin2hex(s1,3,s2);
   hex2bin(s2,s3,&l);
   s3[l] = '\0';
   printf("%s -> %s -> %s\n",s1,s2,s3);
   return 0;
}
