Add support for binary literals in C++
Programming languages such as Python, Ruby and the latest version of Java support binary literals. Binary literals are useful for domains that operate a lot on the bit-level.
It is provided as a compiler extension to C++ in the GCC and Digital Mars compilers and for usefulness and to aid portability I think VC++ should have them too.
Integer constants can be written as binary constants, consisting of a sequence of `0' and `1' digits, prefixed by `0b' or `0B'.
int i = 0b011101010;
The type of these constants follows the same rules as for octal or hexadecimal integer constants, so suffixes like `L' or `UL' can be applied.
If binary literals were implemented it would be useful for the iostreams to have a binary manipulator like dec, hex and oct currently. A "%b" format specifier for the printf/sprintf family would also be very useful. Otherwise, everybody will be rolling their own binary to string conversion functions and classes for this.
As an alternative we could use std::bitset. For example:
const int mybin = std::bitset<32>("10101101").to_ulong()
However, using this method is non-idiomatic and inefficient as the string has to be parsed at runtime.
I am aware that C++0x provides user-defined literals but these are inconvenient as the user has to define their own binary conversion function. Also, everybody will roll their own incompatible binary literals.
There are user-defined literals in C++ already (N2765). For example, you can define 1010101b by simply overloading operator""b.
We don't want Microsoft start inventing anything. All we want for MS to do is simply to impleement the standard. Btw, gcc 4.7 already implemented it.
Ben Voigt [Visual C++ MVP] commented
Let me get this straight.... you're worried about "everyone will roll their own incompatible binary literals", so you're asking MS to roll their own non-standard binary literals?!?
I agree with this but also have 2 further suggestions:
1. allow underscores like 0b0010_0000
2. allow 1b010 syntax as well. "1b" means sign extend the string with 1's to the left.