Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

erlang

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?

like image 329
anonymous Avatar asked Nov 21 '25 10:11

anonymous


1 Answers

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.

like image 184
legoscia Avatar answered Nov 23 '25 15:11

legoscia