Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2014
641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.96 KB | None | 0 0
  1. -- Encoding function
  2.  
  3. local M = {}
  4.  
  5. ---
  6. -- Converts all UTF-8 character sets to unicode/ASCII characters
  7. -- to generate ISO-8859-1 email bodies etc.
  8. --@param utf8 UTF-8 encoded string
  9. --@return a ASCII/ISO-8859-1 8-bit conform string
  10. -- From http://developer.coronalabs.com/code/utf-8-encode-and-decode
  11.  
  12. function M.utf8_decode(utf8)
  13.  
  14.    local unicode = ""
  15.    local mod = math.mod
  16.  
  17.    local pos = 1
  18.    while pos < string.len(utf8)+1 do
  19.  
  20.       local v = 1
  21.       local c = string.byte(utf8,pos)
  22.       local n = 0
  23.  
  24.       if c < 128 then v = c
  25.       elseif c < 192 then v = c
  26.       elseif c < 224 then v = mod(c, 32) n = 2
  27.       elseif c < 240 then v = mod(c, 16) n = 3
  28.       elseif c < 248 then v = mod(c,  8) n = 4
  29.       elseif c < 252 then v = mod(c,  4) n = 5
  30.       elseif c < 254 then v = mod(c,  2) n = 6
  31.       else v = c end
  32.      
  33.       for i = 2, n do
  34.          pos = pos + 1
  35.          c = string.byte(utf8,pos)
  36.          v = v * 64 + mod(c, 64)
  37.       end
  38.  
  39.       pos = pos + 1
  40.       if v < 255 then unicode = unicode..string.char(v) end
  41.  
  42.    end
  43.    
  44.    return unicode
  45. end
  46.  
  47. ---
  48. -- Converts all unicode characters (>127) into UTF-8 character sets
  49. --@param unicode ASCII or unicoded string
  50. --@return a UTF-8 representation
  51. -- From http://developer.coronalabs.com/code/utf-8-encode-and-decode
  52.  
  53. function M.utf8_encode(unicode)
  54.  
  55.    local math = math
  56.    local utf8 = ""
  57.  
  58.    for i=1,string.len(unicode) do
  59.       local v = string.byte(unicode,i)
  60.       local n, s, b = 1, "", 0
  61.       if v >= 67108864 then n = 6; b = 252
  62.       elseif v >= 2097152 then n = 5; b = 248
  63.       elseif v >= 65536 then n = 4; b = 240
  64.       elseif v >= 2048 then n = 3; b = 224
  65.       elseif v >= 128 then n = 2; b = 192
  66.       end
  67.       for i = 2, n do
  68.          local c = math.mod(v, 64); v = math.floor(v / 64)
  69.          s = string.char(c + 128)..s
  70.       end
  71.       s = string.char(v + b)..s
  72.       utf8 = utf8..s
  73.    end
  74.  
  75.    return utf8
  76. end
  77.  
  78.  
  79. return M
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement