Erlang Programming/Bitsyntax

Bit Strings

edit

Erlang lets us use Bit Strings. They have the form

<<Value:Bitlength>> or <<v1:length1,v2:length2,...>>

The default bit length is 8.

65> <<1:8>> == <<1>>. 
true

Integers used in bit strings can be padded on the left with zeroes.

66> <<1:8>> == <<00000001>>. 
true

Some bit strings have string-like representations.

38> <<00011111>>.
<<"g">>

Remember that using the default bit length will cause truncation of too-large integers!

39> <<"g">> == <<103>>.
true
40> <<00011111>> == <<103>>.
true
41> <<00011111:8>> == <<103>>.
true
42> <<00011111:16>> == <<43, 103>>.
true
43> <<00011111:24>> == <<0, 43, 103>>.
true
44> <<00011111:32>> == <<0, 0, 43, 103>>.
true

We cannot specify individual bits with integers. We must use values with a bit length of one.

67> <<0101>>.
<<"e">>
68> <<1:1, 0:1, 1:1>>.
<<5:3>>
69> <<0101>> == <<1:1, 0:1, 1:1>>.
false
70> <<101>> == <<1:1, 0:1, 1:1>>.
false
71> <<1:1, 0:1, 1:1>> == <<5:3>>.
true
72> <<0:5, 1:1, 0:1, 1:1>>.
<<5>>
73> <<0:5, 1:1, 0:1, 1:1>> == <<0101>>.
false

We can select parts of a bit string with pattern matching.

45> <<H:2,T:6>> = <<"A">>. 
<<"A">>
46> H. 
1
47> T.
1 
86> <<01000001:8>> == <<"A">>.
true
87> <<1:2,1:6>> == <<"A">>.
true
88> <<65>> == <<"A">>.
true

We can match X to a value.

95> <<1:2,X:6>> = <<"A">>. 
<<"A">>
96> X.
1

We can not match Y to a bit length.

97> <<1:2,1:Y>> = <<"A">>.
** 1: variable 'Y' is unbound **

We can use a bound variable as a bit length.

98> Z = 6.
6
99> <<1:2,X:Z>> = <<"A">>.
<<"A">>
100> X.
1