[erlang-questions] Bit Syntax and compiler Erlang/OTP R21.1

Fred Hebert mononcqc@REDACTED
Tue Aug 20 21:20:54 CEST 2019


On Tue, Aug 20, 2019 at 2:44 PM Valentin Micic <v@REDACTED> wrote:

>
> Oh, please, don’t get me wrong, I like the ability to write <<World:2,
> Group:2, User:2, *_:2*>> = <<SomeFlags>>.
> However, with this construct, you could still extract your flags, but this
> would not require any new data type (such as bitstring) —  e.g. is_binary(<<World:2,
> Group:2, User:2, *_:2*>> =  <<SomeFlags>>)  will merrily report true.
>
> Contrast this with <<World:2, Group:2, User:2>> = Some6BitBitstring;
>
> which, In order to work, must have Some6BitBitstring set to exactly a
> six-bit Bitstring, which could only be set from within Erlang runtime, thus
> fairly artificial construct with respect to the environment, e.g. OS,
> socket, files, etc.
>
> Thus, my assertion is that bitstring is a pretty pointless data type.
> There.
>

Well, let's take a TCP packet header for example; if you follow the current
wikipedia definition with experimental RFCs, there are 3 reserved bits,
followed by all the flags, set on 9 bits. You could either need to pattern
match all the flags individually, but you can also write, thanks to Erlang
and bitstrings, a function that accepts a pattern like <<..., _Reserved:3,
Flags:9/bits, ...>> and then ask decode_flags(Flags) to return you a list
of atoms for all the values that are set.

This might actually be desirable because some flags change meaning
according to other flags; the ECE flag's value can be triple depending on
whether it is 0, or whether it is 1 and the current value of the SYN flag
being set (1 or 0).

You can obviously work around this, but if you do it C-style, you're likely
to have to gobble the reserved bits along with the flags, and then extract
the experimental flag from the reserved bits, and carry it as an extra
value somewhere.

Mostly, there's interesting stuff that you can do with bitstrings that are
matched-out sections of 8-bit aligned binaries, regardless of where you are
reading them from and what the initial machine alignment was.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190820/ea099c07/attachment.htm>


More information about the erlang-questions mailing list