最近在用Lazarus学写程序,被他的string搞郁闷了,中文乱码,汗一个
没办法了,一咬牙,闹清UTF8大概是杂回事吧,查资料查到这个东东,不错,存个档。
Unicode和UTF-8之间的转换关系表
UCS-4编码 | UTF-8字节流 |
---|---|
U-00000000 – U-0000007F: | 0xxxxxxx |
U-00000080 – U-000007FF: | 110xxxxx 10xxxxxx |
U-00000800 – U-0000FFFF: | 1110xxxx 10xxxxxx 10xxxxxx |
U-00010000 – U-001FFFFF: | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
U-00200000 – U-03FFFFFF: | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
U-04000000 – U-7FFFFFFF: | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
看完上面的东东,在来看这一段程序,会有更深的理解。来自LCLProc。
function UTF8CharacterLength(p: PChar): integer; begin if p<>nil then begin if ord(p^)<%11000000 then begin // regular single byte character (#0 is a character, this is pascal ;) Result:=1; end else if ((ord(p^) and %11100000) = %11000000) then begin // could be 2 byte character if (ord(p[1]) and %11000000) = %10000000 then Result:=2 else Result:=1; end else if ((ord(p^) and %11110000) = %11100000) then begin // could be 3 byte character if ((ord(p[1]) and %11000000) = %10000000) and ((ord(p[2]) and %11000000) = %10000000) then Result:=3 else Result:=1; end else if ((ord(p^) and %11111000) = %11110000) then begin // could be 4 byte character if ((ord(p[1]) and %11000000) = %10000000) and ((ord(p[2]) and %11000000) = %10000000) and ((ord(p[3]) and %11000000) = %10000000) then Result:=4 else Result:=1; end else Result:=1 end else Result:=0; end;