What happens when a bit array segment size is smaller than its value?

Hello!
Sorry if it’s a dumb question but I couldn’t find all the answers I needed from the documentation on bit array expressions. My question is: when I’m building some binary using a literal integer and an explicit size, what happens if the integer is bigger than the specified size?

<<256:1>>

To me it looks like it’s being truncated, only taking the first byte of the number. Another question is, what happens if the literal number is a BigNum stored in the heap instead? Would that change the result because it has a different representation, or would it be as if it were just a “regular” number?
Thanks everyone!

It will be silently truncated. In general, when storing value an integer I into a segment of size N, the actual value stored will be I band ((1 bsl N) - 1).

Your example actually builds a bit string holding one bit. To build a binary holding one byte, you will need to write <<256:8>> or <<256:1/unit:8>>.

It would not change the result. The Erlang language has integers of arbitrary size. The different representations of integers in the runtime system is an implementation detail that the runtime system does its best to hide from you.

2 Likes

Thank you for the answer Björn!

1 Like