lua-users home
lua-l archive

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


It was thus said that the Great Florian Weimer once stated:
> * Michal Kottman:
> 
> > Another (faster) alternative is to avoid the sprintf() call and
> > calculate hex string directly:
> >
> > static char hex[] = "0123456789ABCDEF";
> >
> > ...
> >
> >   for ( p = ns , max = size ; max > 0 ; max--)
> >   {
> > *p++ = hex[*s >> 4];
> > *p++ = hex[*s++ & 0xF];
> >   }
> 
> Caution: this doesn't work with signed chars, you have to change s to
> a pointer to an unsigned char in Sean's code.

  Ah, so it won't.  Anyway, taking this and the other suggestion to use
lua_newuserdata(), I have this:

/*
 * Feel free to use this code
 *
 * Tested under Linux, your milage may vary
 * gcc -Wall -Wextra -pedantic -ansi -g -shared -fpic -o strhex.so strhex.c
 *
 */

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

static const char hex[] = "0123456789ABCDEF";
   
static int strhex(lua_State *L)
{
  const unsigned char *s;
  size_t               size;
  size_t               max;
  char                *ns;
  char                *p;
   
  s  = (const unsigned char *)luaL_checklstring(L,1,&size);
  ns = lua_newuserdata(L,size * 2);

  for ( p = ns , max = size ; max > 0 ; max--)
  {
    *p++ = hex[*s >> 4];         
    *p++ = hex[*s++ & 0x0F];
  }
  
  lua_pushlstring(L,ns,size * 2);
  return 1;
}  

int luaopen_strhex(lua_State *L)
{
  lua_register(L,"strhex",strhex);
  return 0;
}

Old version on my system: 0.66
New version on my system: 0.04

  -spc (I should also mention I've been testing with a 2,150,919 byte file)