> Erlang中文手册 > utf8_list_to_binary/1 把一个 unicode 列表转为一个 utf8 二进制数据

asn1rt:utf8_list_to_binary/1

把一个 unicode 列表转为一个 utf8 二进制数据

用法:

utf8_list_to_binary(UnicodeList) -> {ok,UTF8Binary} | {error,Reason}

内部实现:

%% utf8_list_to_binary/1 transforms a list of integers to a
%% binary. Each element in the input list has the unicode (integer)
%% value of an utf8 character. 
%% The return value is either {ok,Bin} or {error,Reason}. The
%% resulting binary is utf8 encoded.
utf8_list_to_binary(List) ->
    utf8_list_to_binary(List,[]).

utf8_list_to_binary([],Acc) when is_list(Acc) ->
    {ok,list_to_binary(lists:reverse(Acc))};
utf8_list_to_binary([],Acc) ->
    {error,{asn1,Acc}};
utf8_list_to_binary([H|T],Acc) ->
    case catch utf8_encode(H,Acc) of
	NewAcc when is_list(NewAcc) -> 
	    utf8_list_to_binary(T,NewAcc);
	Err -> Err
    end.

把一个整数形式的列表(列表里的每一个整数代表一个字符它对应的 unicode 值)转为一个 UTF8 编码的二进制数据。

asn1rt:utf8_list_to_binary("测试").