linux erlang格式的utf8变为\x(反斜杠x)ascii编码

ui7jx7zq  于 2023-01-16  发布在  Linux
关注(0)|答案(1)|浏览(181)

我想在我的Linux终端上打印一个utf8列表。

-module('main').
-export([main/1]).

main(_) ->
  Text = "あいうえお",
  io:format("~ts~n", [Text]),
  halt().

当我在Ubuntu 22. 04上编译和运行时,

$ erlc main.erl
$ erl -noshell -run main main run
\x{3042}\x{3044}\x{3046}\x{3048}\x{304A}

它显示为\x{3042}而不是\。
在utf8中,“”应该有15个字节,我如何将\x{3042}拆分为3个字节并打印?
顺便说一句,“伊”是个日语字符。
list_to_bin不适用于unicode。
我发现unicode:characters_to_list可以将bin转换为unicode的列表。找不到相反的。

toe95027

toe950271#

如果您想使用Erlang的Unicode输出,那么删除-noshell,添加+pc unicode也是一个好习惯。

$ erl +pc unicode -run main main run
Erlang/OTP 24 [erts-12.2.1] [source] [64-bit] ...

あいうえお

在Erlang中,您可以将二进制指定为utf8。例如,查看日语字符“Ş"的三字节二进制表示。

1> <<"あ"/utf8>>.                                                                          
<<227,129,130>>

在您的示例中,获取字符串的第一个标志符号。

1> Text = "あいうえお".                                                                    
[12354,12356,12358,12360,12362]
2> unicode:characters_to_binary(Text, unicode, utf8).                                      
<<227,129,130,227,129,132,227,129,134,227,129,136,227,129,138>>
3> binary:part(unicode:characters_to_binary(Text, unicode, utf8),0,3).                     
<<227,129,130>>
4> io:format("~ts~n",[binary:part(unicode:characters_to_binary(Text, unicode, utf8),0,3)]).
あ

要将unicode保存到文件中,请使用erlang的文件编码选项。

5>  {ok,G} = file:open("/tmp/unicode.txt",[write,{encoding,utf8}]).
{ok,<0.148.0>}
6> io:put_chars(G,Text).  
ok
7> file:close(G).

然后在一个贝壳里

$ file /tmp/unicode.txt
/tmp/unicode.txt: Unicode text, UTF-8 text, with no line terminators

$ cat /tmp/unicode.txt 
あいうえお

相关问题