NodeMCU下lua的原生字符编码是UTF-8。但是讯飞的语音合成模块xfs5152不支持UTF8,然后NodeMCU也没有提供转码的模块。
也没有找到基于lua代码的转码模块(基于c的有,但是需要手动编译NodeMCU固件)
好在很多模块支持双字节的UNICODE编码,于是只好用lua写了一个UTF8转UNICODE双字节编码的方法,下次找时间把GB2312,GBK的转码也写一下
```
function utf8tounicode(str)
assert(type(str) == "string")
local obj,i,len = {},1,#str
while i<=len do
local c = string.byte(str, i)
local l= c<192 and 1 or c<224 and 2 or c<240 and 3 or --c<248 and 4 or c<252 and 5 or c<254 and 6
error("invalid UTF-8 character sequence")
if l<2 then
table.insert(obj,string.char(c))
table.insert(obj,string.char(0))
i=i+1
else
local o = bit.band(c, 2^(8-l) - 1)
for j=1,l-1 do
c = string.byte(str, i+j)
o = bit.bor(bit.lshift(o, 6), bit.band(c, 63))
end
for j=1,4 do
o1 = bit.band(bit.rshift(o,(j-1)*8),255)
if o1 ~= 0 then
table.insert(obj,string.char(o1))
end
end
i=i+l
end
end
return table.concat(obj)
end
```
网友评论