Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C represent int in base 2 [duplicate]

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.

like image 345
dan.dev.01 Avatar asked Jun 20 '11 15:06

dan.dev.01


1 Answers

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.

like image 70
zneak Avatar answered Sep 24 '22 03:09

zneak