const in binary format

My GNU GCC compiler does not recognize 00111111b due to the end of "b". I tried "B", and it did not work either. Is there any way that I can express and output const in binary format?

It is easy to output in octal and hexdecimal format, and I am wondering how to replace the "oct" in cout statement so that I can print the result in binary form.

Feel free to let me know if you have any ideas.
============================================
1
2
3
4
5
6
7
#include <iostream>
using namespace std;

int main() {
	cout << "00111111b & 00111111b = " << oct
              << (00111111b & 00111111b) << endl;
}

Last edited on
There is not such numeric literal as binary/ So the record (00111111b & 00111111b) is incorrect. You can use hex represenntation of you binary values, for example 0x3F & 0x3F. Though I do not know why you are using the same operands of & operator, because the result will be equal to each of two operands.
There are no binary integer literals in C++. I think hex is often good enough because the digits line up so that each hexadecimal digit represents 4 bits in the number.


EDIT: You can also use std::bitset
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <bitset>

using namespace std;

int main()
{
	bitset<8> a("00111111");
	bitset<8> b("00111111");
	cout << a << " & " << b << " = " << (a & b) << endl;
}
Last edited on
Thanks for both of you guys' suggestions, especially Peter87's, they are really helpful.
bitset<8> a (string("00111111")); is the correct form, and "&" does not apply to bitset operation, we should use " &=" instead.
If the compiler is conforming wrt user defined literals (for instance, GCC 4.7):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template< char FIRST, char... REST > struct binary
{
    static_assert( FIRST == '0' || FIRST == '1', "invalid binary digit" ) ;
    enum { value = ( ( FIRST - '0' ) << sizeof...(REST) ) + binary<REST...>::value  } ;
};

template<> struct binary<'0'> { enum { value = 0 } ; };
template<> struct binary<'1'> { enum { value = 1 } ; };

template<  char... LITERAL > inline
constexpr unsigned int operator "" _b() { return binary<LITERAL...>::value ; }

template<  char... LITERAL > inline
constexpr unsigned int operator "" _B() { return binary<LITERAL...>::value ; }

#include <iostream>

int main()
{
    std::cout << 10101_B << ", " << 011011000111_b << '\n' ; // prints 21, 1735
}
Last edited on
foxatlarge wrote:
... "&" does not apply to bitset operation, we should use " &=" instead.

& can be be used with std::bitset just fine. Just make sure the two operands are both bitsets of the same size.
Topic archived. No new replies allowed.