C represents int in base 2

Possible duplicate:
Is it possible to 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, for example:

(Assuming i has a β€œhuman readable” value of 512. ) Here are the views:

Decimal:

 int i = 512; 

eight-pin:

 int i = 01000; 

hexadecimal:

 int i = 0x200; 

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

Something like int i = 1000000000b ? This is ridiculous, but unfortunately the C compiler does not accept this value.

+7
source share
4 answers

In C (and I believe C ++) there is no binary representation of numbers. However, for the simple number that you display, you can use the shortcut

 int i = 1 << 9; /* binary 1 followed by 9 binary 0 */ 
+8
source

The standard does not describe how to create "binary literals". However, recent versions of GCC and Clang support this function using syntax similar to hex syntax, with the exception of b instead of x :

 int foo = 0b00100101; 

As indicated, using such binary literals blocks you from the Visual Studio C and C ++ compilers, so you can take care of where and how you use them.

C ++ 14 (I know, I know it's not C) standardizes support for binary literals.

+28
source

You cannot do this in C.

But you said you were learning C ++. In C ++, you can use BOOST_BINARY up to C ++ 0x, which will allow user-defined literals .

Please note, however, that it has become very easy to convert hex to binary and vice versa.

For a given binary number, simply group the numbers in groups of four and find out that

 0000 <-> 0 0001 <-> 1 0010 <-> 2 0011 <-> 3 0100 <-> 4 0101 <-> 5 0110 <-> 6 0111 <-> 7 1000 <-> 8 1001 <-> 9 1010 <-> A 1011 <-> B 1100 <-> C 1101 <-> D 1110 <-> E 1111 <-> F 

After several attempts to make this translation, it will become very convenient for you in your head. (Of course, you could do the same with octal, but hex is even more compact than octal.)

In your specific example:

 1000000000 -> 10 0000 0000 -> 0010 0000 0000 -> 0x200 
+11
source

You cannot do this in standard C - the language is not intended to specify integer literals in binary format.

+2
source

All Articles