3 ms·
I use binary literals all the time, for what it's worth, in code involving hardware interfacing. Only complaint with C++14's implementation is that they didn't
by CamperBob2 7y ago
I use binary literals all the time, for what it's worth, in code involving hardware interfacing. Only complaint with C++14's implementation is that they didn't allow underscores to be inserted for clarity, a la Verilog.
Those underscores turn out to be a really big deal, and leaving them out of C++ was a massive mistake. Nobody wants to read constants like 00110100101101011011011101011110, but 00110100_10110101_10110111_01011110 is fine. An implementation of binary constants that doesn't allow this is going to be less popular.
- alexhutcheson 7y agoYou can use ' as the digit separator, like: 0b00110100'10110101'10110111'01011110 It's not ideal, but using underscores was off the table, because things like _100_ are actually valid variable names and it would have caused parsing issues.
- CamperBob2 7y agoThat's cool, I didn't know they supported that. Good enough! Of course, it's not as if '0' wouldn't be ambiguous, so I don't really buy the underscore-as-variable-name argument. C++ left context-free grammar behind a long time ago...
- WalterBright 7y ago_100_ is an identifier in D, too. The simple rule is _ can be embedded in a numeric literal, it just cannot start one.
- alexhutcheson 7y agoActually I got this wrong - the ambiguity occurs with C++11 user-defined literals, not with variable names. See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2747.html http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n274...
- wyldfire 7y agoWould you use a binary literal for a single bit set in a mask? I'd think a `1 << n` would be clearer in that case.
- exmadscientist 7y agoMy favorite use for them is when you've got to set a multi-bit field in a mask or register. If the hardware says bits 25-23 have to be 110 and bits 13-10 have to be 0101, reg = (0b110 << 23) || (0b0101 << 10); is by far the clearest way I know to write that. And since hardware descriptions usually (but not always) give descriptions in binary rather than decimal, it's the easiest form to check against the datasheet or manual.