C represent int in base 2

technology picture technology · Jun 20, 2011 · Viewed 64.9k times · Source

Possible Duplicate:
Can I use a binary literal in C or C++?

I am learning C and i recently found out that we can represent integers in different ways, like that:

(Assuming i has "human-readable" value of 512.) Here are the representations:

Decimal:

int i = 512; 

Octal:

int i = 01000;

Hexadecimal:

int i = 0x200;

In base 2 (or binary representation) 512 is 1000000000. How to write this in C?

Something like int i = 1000000000b? This is funny but unfortunately no C compiler accepts that value.

Answer

zneak picture zneak · Jun 20, 2011

The standard describes no way to create "binary literals". However, the latest versions of GCC and Clang support this feature using a syntax similar to the hex syntax, except it's b instead of x:

int foo = 0b00100101;

As stated, using such binary literals locks you out of Visual Studio's C and C++ compilers, so you may want to take care where and how you use them.

C++14 (I know, I know, this isn't C) standardizes support for binary literals.