algorithm to convert N into base 3 wanted!

Dave Jones djones at megatest.UUCP
Wed Aug 24 08:19:09 AEST 1988


>From article <650003 at hpcilzb.HP.COM>, by tedj at hpcilzb.HP.COM (Ted Johnson):
> Does anyone know of an algorithm to convert a positive integer N into
> its base 3 representation?  (e.g., 14 in base 10 is 112 in base 3).
> 
> Any textbook/journal pointers are appreciated!  (Source code is
> appreciated even more :-)
> 
> -Ted



/* Always happy to help, (if it's this easy). */

#define THREES_MAX 21  /* A number of chars big enough to represent
	               ** any int in base three.  Assuming here 32 bit ints.
                       */

main(argc, argv)
  char** argv;
{
  char threes_rep[THREES_MAX];

  base3(atoi(argv[1]), threes_rep);

  printf("%s\n", threes_rep);

  exit(0);
}

#define digit(num) ((char)(num + '0'))

base3(num, result)
     int num;
     char* result;
{
  int power = 0;
  char backwards[THREES_MAX];
  
  while(num != 0)
    {
      backwards[power++] = digit(num % 3);
      num = num / 3;
    }

  { int rpower = 0;
    
    while(--power >= 0)
      {
	result[rpower++] = backwards[power];
      }
    
    result[rpower] = '\0';
  }
    
}



More information about the Comp.lang.c mailing list