OSDN Git Service

hex encoding functions.
[hmh/hhml.git] / lib / util_string.cc
index c43ac37..baaa19a 100644 (file)
@@ -147,6 +147,18 @@ uint64_t  to_uint64 (const ustring& v) {
     return boost::lexical_cast<uint64_t> (v);
 }
 
+static int  shex (char c) {
+    if ('0' <= c && c <= '9') {
+       return (c - '0');
+    } else if ('a' <= c && c <= 'f') {
+       return (c -  'a' + 10);
+    } else if ('A' <= c && c <= 'F') {
+       return (c - 'A' + 10);
+    } else {
+       return -1;
+    }
+}
+
 static int  hex (char c) {
     if ('0' <= c && c <= '9') {
        return (c - '0');
@@ -945,6 +957,60 @@ uint32_t  hextoul (uiterator b, uiterator e) {
     return ans;
 }
 
+double  hextod (uiterator b, uiterator e, int base) {
+    double  ans = 0.0;
+    int  n;
+    int  c;
+
+    for (n = 0; b < e; n ++, b ++) {
+       c = shex (*b);
+       if (c < 0 || c >= base)
+           return ans;
+       ans = ans * 16. + c;
+    }
+    return ans;
+}
+
+ustring  dtohex (double e, int pad, int base, bool upcase) {
+    double  a, b;
+    int  r;
+    ustring  ans;
+    char  d[128];
+    int  pos;
+    const char*  digs;
+    static const char  xdigsLower[] = "0123456789abcdef";
+    static const char  xdigsUpper[] = "0123456789ABCDEF";
+
+    pos = 128;
+    b = base;
+    if (upcase)
+       digs = xdigsUpper;
+    else
+       digs = xdigsLower;
+    if (e >= 0) {
+       e = floor (e);
+       while (pos > 0 && e > 0) {
+           a = floor (e / b);
+           r = e - a * b;
+           e = a;
+           if (r < 0) {
+               r = 0;
+           } else if (r >= base) {
+               r = base - 1;
+           }
+           d[--pos] = digs[r];
+       }
+       if (pad > 0) {
+           for (int i = 128 - pos; i < pad; i ++) {
+               d[--pos] = '0';
+           }
+       }
+       ans.assign (d + pos, 128 - pos);
+    } else {
+    }
+    return ans;
+}
+
 ustring  toCRLF (const ustring& str) {
     uiterator  b = str.begin ();
     uiterator  e = str.end ();