In c++, we can use hex format to represent a number, for example, for number
70, we can use 0x46, but is there a way to represent a number using the
binary format, something similar to 0x.
No way that I know of in C/C++, but for the record, it can be done
in Perl this way:
0b1000110
or even:
0b0100_0110
(I know this is slightly off-topic, but I thought it worth
mentioning.)
(In case you're wondering, Perl allows the '_' character to be
interspersed in a number, much like we use commas/periods to make big
numbers more readable.)
This has been useful for me several times, as in the past I've had
to check if a byte-value has its second (or third, or fourth...) bit
set. So my code would look like:
if ($byteValue & 0b0100_0000) # check if the second bit is set
{
...
}
Unfortunately, C++ does not support this syntax, so until it does,
I would port the above code from Perl to C++ using hexadecimal values,
like this:
if (byteValue & 0x40) // check if the second bit is set
{
...
}
(Notice that I still keep the comment. Otherwise, the maintainer
who comes after me will have no easy way of knowing if 0x40 has the
bits I intended to check, or if I accidentally created a bug in the
code.)
Of course, you could port that code using octal (by saying
"byteValue & 0100") which isn't really any better or worse than using
hexadecimal. The only difference is that you may have an easier time
with one than the other.
If converting to octal or hexadecimal still leaves a sour taste in
your mouth, your best bet would probably be to write your own function
that takes an input string of 1s and 0s and returns an unsigned long
integer (like some other posters in this thread have suggested). Then
you can write code like this:
if (byteValue & fromBinary("0100 0000")) // check if the second
bit is set
{
...
}
So using hexadecimal, octal, or your own function are three
different "work-arounds" to specifying a binary literal.
I hope this helps, J.W.
-- Jean-Luc