How to generate a 32 bit big-endian number in the format 0x00000001 in erlang

2

I need to generate a variable which has the following properties - 32 bit, big-endian integer, initialized with 0x00000001 (I'm going to increment that number one by one). Is there a syntax in erlang for this?

erlang
asked on Stack Overflow Mar 25, 2019 by hasi

2 Answers

4

In Erlang, normally you'd keep such numbers as plain integers inside the program:

X = 1.

or equivalently, if you want to use a hexadecimal literal:

X = 16#00000001.

And when it's time to convert the number to a binary representation in order to send it somewhere else, use bit syntax:

<<X:32/big>>

This returns a binary containing four bytes:

<<0,0,0,1>>

(That's a 32-bit big-endian integer. In fact, big-endian is the default, so you could just write <<X:32>>. <<X:64/little>> would be a 64-bit little-endian integer.)

On the other hand, if you just want to print the number in 0x00000001 format, use io:format with this format specifier:

io:format("0x~8.16.0b~n", [X]).

The 8 tells it to use a field width of 8 characters, the 16 tells it to use radix 16 (i.e. hexadecimal), and the 0 is the padding character, used for filling the number up to the field width.


Note that incrementing a variable works differently in Erlang compared to other languages. Once a variable has been assigned a value, you can't change it, so you'd end up making a recursive call, passing the new value as an argument to the function. This answer has an example.

answered on Stack Overflow Mar 25, 2019 by legoscia • edited Mar 25, 2019 by legoscia
0

According to the documentation[1] the following snippet should generate a 32-bit signed integer in little endian.

1> I = 258.                              
258
2> B = <<I:4/little-signed-integer-unit:8>>.
<<2,1,0,0>>

And the following should produce big endian numbers:

1> I = 258.
258
2> B = <<I:4/big-signed-integer-unit:8>>.
<<0,0,1,2>>

[1] http://erlang.org/doc/programming_examples/bit_syntax.html


User contributions licensed under CC BY-SA 3.0