Re: creating a binary number

Bob Ippolito <[email protected]>
Newsgroups gmane.comp.lang.erlang.general
Message-ID <CACwMPm9MdLUq3RdKprahvsre-=ZtjY00cOORmKENOiGj-wt_gg@mail.gmail.com>
On Thu, Dec 9, 2021 at 8:04 AM Java House <[email protected]> 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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.