jBee
jBee

Reputation: 193

How to get N bits from binary

I have some binary, how to get N bits from it ? for example: <<2#101>> how to get first bit ?

Upvotes: 0

Views: 1973

Answers (2)

Adam Lindberg
Adam Lindberg

Reputation: 16577

By using binary pattern matching:

1> Bin = <<2#101>>.
<<5>>
2> <<FirstBits:1, Rest/bitstring>> = Bin.
<<5>>
3> FirstBits.
0
4> Rest.
<<5:7>>

The expression FirstBits:1 grabs the first bit. Rest is now 7 bits. You'll need to use bitstring as the type for any binary data as it will not be a multiple of 8 bits anymore (which the binary type enforces).

Looking at the bits individually we can see that Rest is now the last 7 bits of the original binary:

5> bit_size(Bin).
8
6> [Bit || <<Bit:1>> <= Bin]. % Convert the binary to a "bit list"
[0,0,0,0,0,1,0,1]
7> bit_size(Rest).
7
8> [Bit || <<Bit:1>> <= Rest].
[0,0,0,0,1,0,1]

You can use any length to grab a fixed number of bits (e.g. FirstBits:3 to grab the first three bits). The default type is integer if no type is specified. If you want a new binary you can use the type bitstring, like so FirstBits:3/bitstring.

(> <<PrefixNum:3, _/bitstring>> = <<2#01010101>>.
<<"U">>
10> PrefixNum.
2
11> <<PrefixBit:3/bitstring, _/bitstring>> = <<2#01010101>>.
<<"U">>
12> PrefixBit.
<<2:3>>

Upvotes: 9

Michael Kohl
Michael Kohl

Reputation: 66837

Have a look at the Erlang Bit Syntax explanation in the documentation, that should clarify things:

http://www.erlang.org/documentation/doc-5.6/doc/programming_examples/bit_syntax.html

I wrote up a little example using ID3 tags when I started learning Erlang (not that I ever got far in that endeavor):

http://citizen428.net/archives/993

Upvotes: 0

Related Questions