All pastes #147394 Raw Edit

bintime_0.0.1beta

public c v1 · immutable
#147394 ·published 2006-08-24 10:29 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 ASCII 0      */  while (in) {                  /* Fill wih binary digits from LSB to MSB  */    outend--;    switch (in % 2) {      case 0:        *outend = '0'; break;      case 1:        *outend = '1'; break;    }    in = in / 2;  }  while (outend > out) {	/* Fill with '0's until beginning of out   */    outend--;    *outend = '0';  }}void printhelp(char *callname) {  printf("USAGE: %s [-s] [-d] [-h]\n", callname);}int main(int argc, char *argv[]) {  int opt_seconds = 0;  int opt_decimal = 0;  char inarg;  while ((inarg = getopt (argc, argv, "sdhv")) != -1)  switch (inarg) {    case 's':      opt_seconds = 1;      break;    case 'd':      opt_decimal = 1;      break;    case 'h':      printhelp(argv[0]);      return 0;      break;    case 'v':      printf("bintime 0.0.1beta\n");      return 0;      break;    default:      printhelp(argv[0]);      return 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 {			/* Life's much easier without decimal! */    printf(" %s\n%s\n", bin_hour, bin_min);    if (opt_seconds) {      printf("%s\n", bin_sec); }  }  return 0;}