lua-users home
lua-l archive

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


> for ( p = ns , max = size ; max > 0 ; max--)
>   {
>     sprintf(p,"%02X",*s++);
>     p += 2;
>   }

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];
  }

The second loop is more than 10x faster on my computer:

$ lua test.lua 
strhex 6.62
strhex2 0.41

/*
 * Sample code---feel free to use.
 *
 * compiled and tested under Linux
 * gcc -Wall -Wextra -pedantic -ansi -g -shared -fpic -o strhex.so strhex.c
 *
 */

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

static int strhex(lua_State *L)
{
  const char *s;
  size_t      size;
  size_t      max; 
  char       *ns;  
  char       *p;  
  
  s  = luaL_checklstring(L,1,&size);
  ns = lua_newuserdata(L, size * 2 + 1);

  for ( p = ns , max = size ; max > 0 ; max--)
  {
    sprintf(p,"%02X",*s++);
    p += 2;
  }
   
  lua_pushlstring(L,ns,size * 2);
  return 1;
}

static char hex[] = "0123456789ABCDEF";
static int strhex2(lua_State *L)
{
  const char *s;
  size_t      size;
  size_t      max; 
  char       *ns;  
  char       *p;  
  
  s  = 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++ & 0xF];
  }
   
  lua_pushlstring(L,ns,size * 2);
  return 1;
}

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

local clock = os.clock;

a = ("/"):rep(1e7);
collectgarbage "stop"

local t = clock();
for i = 1, 5 do
  strhex(a);
end
print("strhex", clock() - t);

local t = clock();
for i = 1, 5 do
  strhex2(a);
end
print("strhex2", clock() - t);

local s1 = strhex(a)
local s2 = strhex2(a)
assert(s1 == s2, "hex strings are different!")