如何在Lua中将字符串字符转换为字符编码?
获取字符串字符对应的字符编码方法
Lua 实现方式
你用str:sub(150, 150)取出单个字符后,可通过以下方式获取编码:
- 若只需获取字符的单字节编码(ASCII或UTF-8单字节字符),直接使用
string.byte()函数:
local str = "你的目标字符串" local single_char = str:sub(150, 150) local char_code = string.byte(single_char) print(char_code)
- 若处理的是UTF-8多字节字符,要获取完整Unicode码点,可自定义函数解析:
function utf8_char_to_code(char) local bytes = {string.byte(char, 1, -1)} local code = 0 if #bytes == 1 then code = bytes[1] elseif #bytes == 2 then code = (bytes[1] - 0xC0) * 0x40 + (bytes[2] - 0x80) elseif #bytes == 3 then code = (bytes[1] - 0xE0) * 0x1000 + (bytes[2] - 0x80) * 0x40 + (bytes[3] - 0x80) elseif #bytes == 4 then code = (bytes[1] - 0xF0) * 0x40000 + (bytes[2] - 0x80) * 0x1000 + (bytes[3] - 0x80) * 0x40 + (bytes[4] - 0x80) end return code end local utf8_char = str:sub(150, 150) -- 确保取出的是完整UTF-8字符 local unicode_code = utf8_char_to_code(utf8_char) print(unicode_code)
Python 实现方式
Python中直接用ord()函数获取字符的Unicode码点:
str = "你的目标字符串" single_char = str[149] # Python为0索引,对应Lua的第150位字符 char_code = ord(single_char) print(char_code)
JavaScript 实现方式
根据需求选择charCodeAt()或codePointAt():
charCodeAt()返回UTF-16编码单元(适用于基本多语言平面字符)codePointAt()返回完整Unicode码点(支持代理对字符)
let str = "你的目标字符串"; let charCode = str.charCodeAt(149); // 0索引 let codePoint = str.codePointAt(149); console.log(charCode, codePoint);
内容的提问来源于stack exchange,提问作者user123454321
相关产品推荐
相关产品推荐

