move all code relative to readline into separate file (2)
[calc.git] / format.c
index 152875022ad8a10f826378c7d611a5abd5d6edd4..60cb1d477e6055281b578070daf7cae63bfc75d0 100644 (file)
--- a/format.c
+++ b/format.c
@@ -6,6 +6,9 @@
 
 /* global variables */
 
+int _ibase = 10;
+int _obase = 10;
+
 #define DEFAULT_FORMAT "=> %.6g\n"
 char *_format = NULL;
 #define DEFAULT_MINFORM "%.6g"
@@ -67,17 +70,66 @@ void free_format ()
     }
 }
 
+void set_base (int in, int out)
+{
+    _ibase = in;
+    _obase = out;
+}
+
+char *show_base ()
+{
+    static char str[16] = {0};
+    sprintf (str, "%d/%d", _ibase, _obase);
+    return str;
+}
+
+int get_ibase ()
+{
+    return _ibase;
+}
+
+/* multi base integer to ascii function */
+
+char *mbitoa (unsigned long value)
+{
+    static char str[8 * sizeof (long) + 1];
+
+    /* decompose */
+    char buffer[8 * sizeof (long) + 1] = {0};
+    int size = 0;
+    do {
+        char x = value % _obase;
+        buffer[size++] = (x > 9) ? 'a' + x - 10 : '0' + x;
+        value /= _obase;
+    } while (value != 0);
+
+    /* revert */
+    int i;
+    for (i = 0; i < size; i++) {
+        str[i] = buffer [size - i - 1];
+    }
+    str[size] = '\0';
+
+    return str;
+}
+
 double print (double value)
 {
-    fprintf (stdout, _format ? _format : DEFAULT_FORMAT, value);
-    fflush (stdout);
+    if (_obase == 10) {
+        printf (_format ? _format : DEFAULT_FORMAT, value);
+    } else {
+        printf ("%s%s\n", (_prompt) ? _prompt : DEFAULT_PROMPT, mbitoa ((unsigned int)value));
+    }
     return value;
 }
 
 double printl (double value)
 {
-    fprintf (stdout, _minform ? _minform : DEFAULT_MINFORM, value);
-    fflush (stdout);
+    if (_obase == 10) {
+        printf (_minform ? _minform : DEFAULT_MINFORM, value);
+    } else {
+        printf ("%s", mbitoa ((unsigned int)value));
+    }
     return value;
 }