erlang的汉字字符串和二进制的相互转换,并还原成汉字打印

 测试:

1> Hanzi = <<”汉字”/utf8>>.
<<230,177,137,229,173,151>>
2> io:format(“~ts”,[Hanzi]).
汉字ok
3> io:format(“~w”,[Hanzi]).
<<230,177,137,229,173,151>>ok
22> unicode:characters_to_binary(“中国”).
<<228,184,173,229,155,189>>

结论:

中文字符,在Erlang的存储方式,可以是List,也可以是Binary。

如果以List方式存储,即将中文字符,转为Unicode编码(长整数格式);

如果以Binary方式存储,即将中文字符,转为UTF-8编码。

至于Unicode与UTF-8的区别,简单来说,Unicode是一个码表,UTF-8是Unicode编码的一种表示方法。具体的区别,大家可问下谷歌或度娘。

例子:

start() ->
Str = “中国”,
io:format(“Unicode list is: ~p~n”, [Str]),
Bin = unicode:characters_to_binary(Str),
io:format(“Unicode binary is: ~p~n”, [Bin]),
Str1 = unicode:characters_to_list(Bin, utf8),
io:format(“utf8 binary to list is: ~p~n”, [Str1]).

输出结果:

Eshell V6.4 (abort with ^G)
([email protected])1> Unicode list is: [20013,22269]
([email protected])1> Unicode binary is: <<228,184,173,229,155,189>>
([email protected])1> utf8 binary to list is: [20013,22269]
([email protected])1>

其中用到了unicode库函数,如果使用普通的erlang:list_to_binary或erlang:binary_to_list,会有编码问题。

在开发过程中,使用的一些第三方库,对中文支持或多或少都有些问题,各位按照此规则调试,可以解决。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章