3

我生成这样的对象 ID:mongodb_app:gen_objectid() 这显然返回一个 ObjectId 类型。

我需要一个 BinType(3, ...) 因为我们不存储 objectids 而是二进制子类型 3 ids。

有谁知道如何转换这个?

4

2 回答 2

3
%%This method is used to generate ObjectId from binary string.
binary_string_to_objectid(BinaryString) ->
    binary_string_to_objectid(BinaryString, []).

binary_string_to_objectid(<<>>, Result) ->
    {list_to_binary(lists:reverse(Result))};
binary_string_to_objectid(<<BS:2/binary, Bin/binary>>, Result) ->
    binary_string_to_objectid(Bin, [erlang:binary_to_integer(BS, 16)|Result]).

%%This method is used to generate binary string from objectid.
objectid_to_binary_string({Id}) ->
    objectid_to_binary_string(Id, []).

objectid_to_binary_string(<<>>, Result) ->
    list_to_binary(lists:reverse(Result));
objectid_to_binary_string(<<Hex:8, Bin/binary>>, Result) ->
    StringList1 = erlang:integer_to_list(Hex, 16),
    StringList2 = case erlang:length(StringList1) of
        1 ->
            ["0"|StringList1];
        _ ->
            StringList1
    end,
    objectid_to_binary_string(Bin, [StringList2|Result]).

测试示例:

binary_string_to_objectid(<<"51F5BE99118735B187000001">>)。
输出:
{<<81,245,190,153,17,135,53,177,135,0,0,1>>}

objectid_to_binary_string({<<81,245,190,153,17,135,53,177,135,0,0,1>>})。
输出:
<<"51F5BE99118735B187000001">>

于 2013-10-07T10:47:28.713 回答
0

想出了如何解决它,我使用来自 avtobiff 的 uuid 生成器来生成 UUID:

generate_objectid_subtype3() ->
    {bin, uuid, uuid:uuid4()}.
于 2012-07-19T05:44:20.803 回答