How do I get binary byte length in Erlang?

0xAX picture 0xAX · Apr 18, 2011 · Viewed 12k times · Source

If I have the following binary:

<<32,16,10,9,108,111,99,97,108,104,111,115,116,16,170,31>>

How can I know what length it has?

Answer

Adam Lindberg picture Adam Lindberg · Apr 18, 2011

For byte size:

1> byte_size(<<32,16,10,9,108,111,99,97,108,104,111,115,116,16,170,31>>).
16

For bit size:

2> bit_size(<<32,16,10,9,108,111,99,97,108,104,111,115,116,16,170,31>>).
128

When you have a bit string (a binary with bit length not divisible by the byte size 8) byte_size/1 will round up to the nearest whole byte. I.e. the amount of bytes the bit string would fit in:

3> bit_size(<<0:19>>).
19

4> byte_size(<<0:19>>). % 19 bits fits inside 3 bytes
3

5> bit_size(<<0:24>>).
24

6> byte_size(<<0:24>>). % 24 bits is exactly 3 bytes
3

7> byte_size(<<0:25>>). % 25 bits only fits inside 4 bytes
4

Here's an example illustrating the difference in sizes going from 8 bits (fits in 1 byte) to 17 bits (needs 3 bytes to fit):

8> [{bit_size(<<0:N>>), byte_size(<<0:N>>)} || N <- lists:seq(8,17)].
[{8,1},
 {9,2},
 {10,2},
 {11,2},
 {12,2},
 {13,2},
 {14,2},
 {15,2},
 {16,2},
 {17,3}]