I am trying to implement the following python code and get the same result in Erlang:
struct.pack('Q', long(20000001))
Any ideas?
The closest equivalent to pack
/unpack
in Erlang is achieved using the bit syntax.
As the Q
format is mapped to the 8 bytes unsigned long long
by (un)pack, you might obtain something similar by writing:
40> <<V:64>>.
<<0,0,0,0,1,49,45,1>>
Notice that in Erlang the default endianess is big-endian. You might want to change that (or mention it explicitly):
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>>
You can perform the reverse operation using the same syntax (here specifying explicitly the signedness):
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
Please note the standard output of binary values might be confusing at first sight when comparing Python to Erlang:
Python Erlang
\x00 => <<0>>
\x01 => <<1>>
- => <<45>>
1 => <<49>> ! do not confuse the value 1 (0x01) and the character '1' !
So, the Python binary string \x01-1\x01\x00\x00\x00\x00
is written <<1, 45, 49, 1, 0, 0, 0, 0>>
in Erlang.