// calc_bin_rep_solution2.c - Alternate solution for the example
//                            that uses Strings

#include <stdio.h>
#include <stdlib.h>

// function declarations

int readInt(char *prompt);
char *calculateBinRep(int num);
void writeString(char *str);

void exitOnFatalErrorOutOfMemory();

//------------------------------------------------------------

int main()
{
  char *binrep = calculateBinRep(readInt(
    "Please enter a number: "));
  writeString(binrep);
  writeString("\n");
  free(binrep);
  return(0);
}

//------------------------------------------------------------

int readInt(char *prompt)
{
  int input = 0;
  writeString(prompt);
  scanf("%d",&input);
  return(input);
}

//------------------------------------------------------------
void writeString(char *str)
{
  printf("%s",str);
}

//------------------------------------------------------------
char *calculateBinRep(int num)
{
  char *help = NULL;
  unsigned bitmask = 0x1 << ((sizeof(int) * 8) - 1);
  char *binrep = malloc((sizeof(char) * sizeof(int) * 8) + 1);
  if (!binrep)
    exitOnFatalErrorOutOfMemory();
  help = binrep;
  while(bitmask)
  {
    *help++ = (num & bitmask) ? '1' : '0';
    bitmask >>= 1;
  }
  *help = '\0';
  return(binrep);
}

//------------------------------------------------------------
void exitOnFatalErrorOutOfMemory()
{
  printf("Fatal Error: Out of Memory\n");
  exit(-1);
}
