5 ms·
>C++14 brings core language support for binary literals, which means you now can integrate binary literals as such in your code: >char c = 0b01011010 I can't
by diydsp 13y ago
>C++14 brings core language support for binary literals, which means you now can integrate binary literals as such in your code:
>char c = 0b01011010
I can't believe this took TWENTY YEARS (or at least that's how long I personally have been waiting). Hurray! (I'm going to hobble my walker over to the desktop and start codin' binary.)
- kps 13y agoBoost has a macro that's usable in plain C as well, since it uses only the preprocessor. #include <boost/utility/binary.hpp> char c = BOOST_BINARY(01011010);
- stingraycharles 13y agoYeah but that is a but similar as BOOST_FOREACH before c++11 -- it just isn't making things any prettier. I think most people nowadays are conditioned to parse the enum-as-bitmasks 0x01, 0x02, 0x04, 0x08 etc, so i would be reluctant to use boost's version in that case. The new operator, however, seems pretty sweet for that use case!
- pkrumins 13y agoHere's one of my all-time favorite way to write binary literals in C by abusing define: #define HEXIFY(X) 0x##X##LU #define B8IFY(Y) (((Y&0x0000000FLU)?1:0) + \ ((Y&0x000000F0LU)?2:0) + \ ((Y&0x00000F00LU)?4:0) + \ ((Y&0x0000F000LU)?8:0) + \ ((Y&0x000F0000LU)?16:0) + \ ((Y&0x00F00000LU)?32:0) + \ ((Y&0x0F000000LU)?64:0) + \ ((Y&0xF0000000LU)?128:0)) #define B8(Z) ((unsigned char)B8IFY(HEXIFY(Z))) And now you can write: B(01011010) Etc. If you like this, see my blog post about bithacks.h: http://www.catonmat.net/blog/bit-hacks-header-file/ http://www.catonmat.net/blog/bit-hacks-header-file/
- dbaupp 13y agoUsing octal (0o) gives you larger representable numbers, fwiw.
- deletes 13y agoThere is no need for binary literals. Every low level programmer should know the first 16 hexadecimals in his sleep. With that you can simply do char c = 0x5A. It is more readable since there are more distinguishing characters and is shorter. I actually made a mistake when I first scanned your numbers and had to look carefully. Imagine if the number was a 64bit integer. Also <bitset>, if you intend to use c++ correctly.
- Someone 13y agoYou shouldn't use binary everywhere, just like you shouldn't just hex everywhere. Binary literals make sense for bit data. For example, coding an icon for a game: char unsigned bottomLeftCorner[8] = { 0b11000000, 0b11000000, 0b11000000, 0b11000000, 0b11000000, 0b11000000, 0b11111111, 0b11111111 }; They may, at times, also make sense when coding some low-level protocol.