Hacker News new | ask | show | jobs
by klibertp 1541 days ago
In my experience the best for "bit-fiddling" is Erlang (and, by extension, Elixir) which offers bit-string literals[1], along with pattern matching on them. It's trivial to implement any binary protocol or parse any binary file format with these. It makes bit-fiddling pleasant and fun, but nobody ever mentions Erlang in these discussions.

That's because most programmers are incapable of making any informed decision about the language they use (and, even more so, about languages they don't use). There's a strong tribal mentality, a lot of cargo-cults, and the very narrow perspective on what's possible and (more importantly) what's desirable is prevalent.

[1] https://www.erlang.org/doc/programming_examples/bit_syntax.h...

1 comments

Common Lisp has bit string literals:

    Welcome to Clozure Common Lisp Version 1.11-r16812M  (DarwinX8664)!
    
    ? #*010010010101001
    #*010010010101001
    ? (type-of *)
    (SIMPLE-BIT-VECTOR 15)
I think it's not unusual to have base-x number literals (even Python got `0b01101` literals at some point), but not many languages support pattern matching on bitstrings. In Erlang, it looks like this:

    1> A = 2#0010010010101001.
    9385
    2> << _:2, B:4, _/bitstring >> = << A:16 >>, B.
    9
    3> io:format("~.2B~n", [B]).
    1001
I put your number into 16-bit bitstring[1], then ignored first 2 bits, extracted the next 4 bits, and ignored the rest.

CL doesn't have pattern matching in the standard, IIRC, but there are libraries implementing it, so I wouldn't be surprised if one of them also offered bitstring matching, but that's beside the point: I'm comparing Erlang and C++ here, not Erlang and CL.

[1] It could be 14 or 15 bits, but I wanted to have a bit of a leading padding to ignore in the pattern.

EDIT: I missed the fact that the #*01... literal in CL is not a number, my bad. The equivalent literal would be << 2#01...:N >> in Erlang, but you need to give the N (number of bits) yourself, so it's a bit less convenient.