lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


After all this talk we sat down and added hex/bin/oct support for uCore -
this is the code for everybody to comment - this is the luaO_str2d function
in lobject.c and it simply states that if a string starts with 0x 0b 0o it
uses a different base to convert the numbers.

/Erik

double luaO_str2d (lua_State *lua_state,char *s) {  /* LUA_NUMBER */
  double a = 0.0;
  int point = 0;
  // Hex Number support
  if (s[0] == '0' && (s[1] == 'x' || s[1] == 'b' || s[1] == 'o'))
  {
    char *ss;
    int   base;
    int   n;
    switch(s[1])
    {
      case 'x':
        base = 16;
        break;
      case 'b':
        base = 2;
        break;
      case 'o':
        base = 8;
        break;
    }
    n = strtol(&s[2], &ss,base);
    if (ss != &s[2])
      return (double)n;
    else
      return -1;
  }
  // End Hex
  while (isdigit((unsigned char)*s)) {
    a = 10.0*a + (*(s++)-'0');
  }
  if (*s == '.') {
    s++;
    while (isdigit((unsigned char)*s)) {
      a = 10.0*a + (*(s++)-'0');
      point++;
    }
  }
  if (toupper((unsigned char)*s) == 'E') {
    int e = 0;
    int sig = 1;
    s++;
    if (*s == '-') {
      s++;
      sig = -1;
    }
    else if (*s == '+') s++;
    if (!isdigit((unsigned char)*s)) return -1;  /* no digit in the
exponent? */
    do {
      e = 10*e + (*(s++)-'0');
    } while (isdigit((unsigned char)*s));
    point -= sig*e;
  }
  while (isspace((unsigned char)*s)) s++;
  if (*s != '\0') return -1;  /* invalid trailing characters? */
  if (point > 0)
    a /= expten(L,point);
  else if (point < 0)
    a *= expten(L,-point);
  return a;
}