# creating a binary number

Bob Ippolito bob@REDACTED
Thu Dec 9 21:49:44 CET 2021

```On Thu, Dec 9, 2021 at 8:04 AM Java House <java4dev@REDACTED> wrote:

> Hello
>
> I am trying to build a binary number but I cannot find the correct way:
> 13> <<1:1/bitstring,
> 0:1/bitstring,0:1/bitstring,0:1/bitstring,0:1/bitstring,0:1/bitstring,0:1/bitstring,0:1/bitstring>>.
> ** exception error: bad argument
>      in function  eval_bits:eval_exp_field1/6 (eval_bits.erl, line 123)
>      in call from eval_bits:create_binary/2 (eval_bits.erl, line 81)
>      in call from eval_bits:expr_grp/4 (eval_bits.erl, line 72)
>
> How do we build a binary number e.g.
> 10000000 or 10101010 or even a binary number that is not just 8 bit but
> 12, 14 or 17 bit long
>

I think the confusion here is that there is a type called binary for
dealing with bits/bytes/words and there's also the binary number system
(base 2). You don't need the binary type or binary syntax to work with
integers in base 2.

To write an integer literal in radix 2 (binary):

> 4095 =:= 2#111111111111.

true

You can also use that syntax (or any other way to represent an integer)
when constructing a binary (note the bit length of 12).

> <<2#111111111111:12>>.

<<255,15:4>>

If, for some reason, you wanted to construct it a bit at a time:

> <<1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:1>> =:=
<<2#111111111111:12>>.

true

The /bitstring modifier is not really relevant to this, it is for
constructing or destructing a larger binary from other binaries that may
not have a multiple-of-eight length.

>

<<<<1:1>>/bitstring, <<1:1>>/bitstring, <<1:1>>/bitstring,
<<1:1>>/bitstring, <<1:1>>/bitstring, <<1:1>>/bitstring, <<1:1>>/bitstring,
<<1:1>>/bitstring, <<1:1>>/bitstring, <<1:1>>/bitstring, <<1:1>>/bitstring,
<<1:1>>/bitstring>> =:= <<2#111111111111:12>>..

To display integers in base 2, you could use integer_to_list/2 or
integer_to_binary/2 or a format string.

> integer_to_list(4095, 2).

"111111111111"

> integer_to_binary(4095, 2).

<<"111111111111">>

> io_lib:format("~.2B", [4095]).

"111111111111"

-bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20211209/0911a32a/attachment.htm>
```