Skip to content

Instantly share code, notes, and snippets.

@MikuAuahDark
Last active December 27, 2022 03:58
Show Gist options
  • Save MikuAuahDark/124c89af9f2d4874c347 to your computer and use it in GitHub Desktop.
Save MikuAuahDark/124c89af9f2d4874c347 to your computer and use it in GitHub Desktop.
[Lua] Unicode code point to UTF-8 sequence
---@param code integer
function cp2seq(code)
if code <= 0x7F then
-- 0xxxxxxx
return string.char(code)
elseif code <= 0x7FF then
-- 110xxxxx 10xxxxxx
return string.char(
0xC0 + math.floor(code / 0x40),
0x80 + code % 0x40)
elseif code <= 0xFFFF then
-- 1110xxxx 10xxxxxx 10xxxxxx
return string.char(
0xE0 + math.floor(code / 0x1000),
0x80 + math.floor(code / 0x40) % 0x40,
0x80 + code % 0x40
)
elseif code <= 0x1FFFFF then
-- 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
return string.char(
0xF0 + math.floor(code / 0x40000),
0x80 + math.floor(code / 0x1000) % 0x40,
0x80 + math.floor(code / 0x40) % 0x40,
0x80 + code % 0x40
)
else
return ""
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment