将Python struct.pack转换为erlang

时间:2015-03-24 07:40:34

标签: python erlang pack

我正在尝试实现以下python代码并在Erlang中获得相同的结果:

struct.pack('Q', long(20000001))

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

使用bit syntax在Erlang中与pack / unpack最接近的等价物。

Q格式映射到8个字节unsigned long long by(un)pack时,您可以通过编写来获得类似的东西:

40> <<V:64>>.
<<0,0,0,0,1,49,45,1>>

请注意,在Erlang中,默认的endianess是big-endian。您可能想要更改它(或明确提及):

41> <<V:64/big>>.
<<0,0,0,0,1,49,45,1>>

42> <<V:64/little>>.       %% <= Given your example, probably what you want.
<<1,45,49,1,0,0,0,0>>

43> <<V:64/native>>.       %% <= Native endianness 
                           %% -- dependent of the CPU Erlang is running on.
<<1,45,49,1,0,0,0,0>>

您可以使用相同的语法(此处明确指定签名)执行反向操作:

44> <<B:64/unsigned-big>> = <<V:64>>. %% big-endian (default) to big-endian
45> B.
20000001

46> <<S:64/unsigned-little>> = <<V:64>>. %% big-endian to little-endian
47> S.
84777848354635776

48> <<L:64/unsigned-little>> = <<V:64/little>>. %% little-endian to little-endian
<<1,45,49,1,0,0,0,0>>
49> L.                                         
20000001

请注意,在将Python与Erlang进行比较时,二进制值的标准输出可能会引起混淆:

Python      Erlang
\x00    =>  <<0>>
\x01    =>  <<1>>
-       =>  <<45>>
1       =>  <<49>>  ! do not confuse the value 1 (0x01) and the character '1' !

因此,Python二进制字符串\x01-1\x01\x00\x00\x00\x00在Erlang中编写<<1, 45, 49, 1, 0, 0, 0, 0>>