Bee

2009年10月25日 #

一段转换guid字符串的lua代码

 

--guid2.lua
--= "{0xCC3F04F7, 0x3198, 0x407E, {0xA0, 0x05, 0x73, 0xBA, 0xB6, 0xD3, 0xC2, 0x67} }"
= "CC3F04F7-3198-407E-A005-73BAB6D3C267"
-- 通过flag表来控制将纯32位数字纯转换为什么格式的guid串
function convert_with_flags(s_guid, tblflags)
 
if string.len(s_guid) ~= 32 or type(tblflags) ~= "table" then
  error 
"parameter is invalid"
  
return
 end
 local s_ret 
= ""
 local n_elements 
= table.getn(tblflags)
 
for i = 1, n_elements, 1 do
  
if type(tblflags[i]) == "string" then
   s_ret 
= s_ret..tblflags[i]
  elseif type(tblflags[i]) 
== "table" then
   s_ret 
= s_ret..string.sub(s_guid, tblflags[i][1], tblflags[i][2])
  end
 end
 
return s_ret
end
-- 将guid字符串转换成32位数字串
function make_pure_guid(s)
 local s_pure 
= string.gsub(string.upper(s), "0X""")
 s_pure 
= string.gsub(s_pure, "%X""")
 
return s_pure
end
function convert2cstyle(s)
 local s_pure 
= make_pure_guid(s)
 
if string.len(s_pure) ~= 32 then
  error 
"invalid guid string"
  
return
 end
 local tbl_flags 
= {"{0x"{18}", 0x"{912}", 0x"1316},
     
", {0x"{1718}", 0x"{1920}", 0x"{2122},
     
", 0x"{2324}", 0x"{2526}", 0x"{2728},
     
", 0x"{2930}", 0x"{3132}"} }"
    }

 
return convert_with_flags(s_pure, tbl_flags)
end
function convert2normal(s)
 local s_pure 
= make_pure_guid(s)
 
if string.len(s_pure) ~= 32 then
  error 
"invalid guid string"
  
return
 end
 local tbl_flags 
= {{18}"-"{912}"-"1316},
     
"-"{1720}"-"{2132}
    }

 
return convert_with_flags(s_pure, tbl_flags)
end
print(
"s = "..s)
s_guid_normal 
= convert2normal(s)
print(
"s_guid_normal = "..s_guid_normal)
s_guid_cstyle 
= convert2cstyle(s_guid_normal)
print(
"s_guid_cstyle = "..s_guid_cstyle)

posted @ 2009-10-25 12:56 Bee 阅读(877) | 评论 (0)编辑 收藏

仅列出标题