Skip to content

Instantly share code, notes, and snippets.

@cristobal
Last active December 16, 2015 17:39
Show Gist options
  • Select an option

  • Save cristobal/5471683 to your computer and use it in GitHub Desktop.

Select an option

Save cristobal/5471683 to your computer and use it in GitHub Desktop.
UCS2 encode a string for sending via AT modem using `%04x` hex format.
local function ucs2_encode(str)
local cc = {}
local bv = {1, 2, 4, 8, 16, 32, 64, 128}
local fmt = "%04x"
-- bit_set taken from http://ricilake.blogspot.no/2007/10/iterating-bits-in-lua.html
local function bit_set(x, p)
return x % (p + p) >= p
end
-- get bit_val
-- x the number
-- n the max bit bit are enumerated 1..8 instead of 0..7 lua world
-- i the start bit pos
-- o offset shift up/down
local function bit_val(x, n, i, o)
local v = 0
if not i then
i = 1
end
if not o then
o = 0
end
while i <= n do
if bit_set(x, bv[i]) == true then
v = v + bv[i + o]
end
i = i + 1
end
return v
end
-- encode string
local i = 1
local n = str:len()
local c, c2, o, v
while i <= n do
-- read 1st byte, if uses one byte we got the char code
-- otherwise read 2nd byte and compute new char code
c = str:byte(i)
o = 1
-- @see http://en.wikipedia.org/wiki/UTF-8 for UTF8-2
if c > 127 then
-- read 2nd lower byte
-- compute new char code value
c2 = str:byte(i + 1)
c = bit_val(c, 5, 3, -2) +
bit_val(c, 2, 1, 6) +
bit_val(c2, 6)
o = 2
end
table.insert(cc, string.format(fmt, c))
i = i + o
end
return string.upper(table.concat(cc, ""))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment