All pastes #145351 Raw Edit

Something

public c v1 · immutable
#145351 ·published 2006-08-22 23:07 UTC
rendered paste body
#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <time.h>/* See http://en.wikipedia.org/wiki/Binary_numeral_system#Decimal for the  *//* principle of the conversion algorithm used here.                        */void dec2binstr(int in, char *out, int outlen) {  char *outend = out + outlen;	/* Initialize a pointer to work the string */  *outend = '\0';		/* from behind and insert the terminating  */  outend--;			/* ASCII 0.                                */  while (outend > out) {    while (in) {      switch (in % 2) {        case 0:          *outend = '0'; break;        case 1:          *outend = '1'; break;      }      in = in / 2;      outend--;    }    *outend = '0';    outend--;  }  *outend = '0'; /* Don't outend--; after the last pass, so it's not left  */                 /* pointing to an invalid memory location. Could this be  */                 /* the fix for the problem with gcc 4?                    */}int main(int argc, char *argv[]) {  int opt_seconds = 0;  int opt_decimal = 0;  char inarg;  while ((inarg = getopt (argc, argv, "sd")) != -1)  switch (inarg) {    case 's':      opt_seconds = 1;      break;    case 'd':      opt_decimal = 1;      break;  }  time_t curtime;  struct tm *timedata;  curtime = time(0);  timedata = localtime(&curtime);  int twelve_hour;  char bin_hour[5];   /* only four digits for the hour */  char bin_min[7];  char bin_sec[7];  twelve_hour = timedata->tm_hour;  if (twelve_hour > 12) { twelve_hour -= 12; }  dec2binstr(twelve_hour, bin_hour, 4);  dec2binstr(timedata->tm_min, bin_min, 6);  if (opt_seconds) { dec2binstr(timedata->tm_sec, bin_sec, 6); }  /* I thought a lot about how to do this and I've decided to rather go *   * with a bunch of printf(); lines than to do some kind of smartass   *   * printf("%s  %s\n", bin_min, dec_min) black voodoo thing, because   *   * that would involve initializing an empty dec_min string and then   *   * filling it if needed. And since this is C and not Perl, that would *   * be Shooting Myself In The Foot(tm) big time.                       */  if (opt_decimal) {    if (timedata->tm_hour < 10) {      printf(" %s   (0%ih)\n", bin_hour, timedata->tm_hour); }    else {      printf(" %s   (%ih)\n", bin_hour, timedata->tm_hour); }    if (timedata->tm_min < 10) {      printf("%s  (0%im)\n", bin_min, timedata->tm_min); }    else {      printf("%s  (%im)\n", bin_min, timedata->tm_min); }    if (opt_seconds) {      if (timedata->tm_sec < 10) {        printf("%s  (0%is)\n", bin_sec, timedata->tm_sec); }      else {        printf("%s  (%is)\n", bin_sec, timedata->tm_sec); }    }  }  else {    printf(" %s\n%s\n", bin_hour, bin_min);    if (opt_seconds) {      printf("%s\n", bin_sec); }  }  return 0;}