/* 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>

void outdec(int v)
{
  printf("decimal = %d\n",v);
}

void outhex(int v)
{
  printf("hexadecimal = %X\n",v);
}

int inbin_1(char *s)
{
  int res,ix;
  ix=0;
  res = 0;
  while(s[ix]!='\0')
  {
    if(s[ix]!='1' && s[ix]!='0') return -1;
    res = res * 2 + (s[ix]=='1' ? 1 : 0);
    ix++;
  }
  return res;
}

int inbin_2(char *s)
{
   char *ep;
   int v;
   v = strtol(s, &ep, 2);
   if(ep >= (s+strlen(s)))
   {
      return v;
   }
   else
   {
      return -1;
   }
}

void test(char *s)
{
   int v;
   printf("testing %s\n",s);
   v = inbin_1(s);
   if(v >=0)
   {
      outdec(v);
      outhex(v);
   }
   else
   {
      printf("fejl\n");
   }
   v = inbin_2(s);
   if(v >=0)
   {
      outdec(v);
      outhex(v);
   }
   else
   {
      printf("fejl\n");
   }
}

int main()
{
   test("1100");
   test("123");
   return 0;
}
