Can I use a binary literal in C or C++?

前端 未结 19 2640
梦如初夏
梦如初夏 2020-11-22 07:40

I need to work with a binary number.

I tried writing:

const x = 00010000;

But it didn\'t work.

I know that I can use an hex

19条回答
  •  迷失自我
    2020-11-22 08:04

    As already answered, the C standards have no way to directly write binary numbers. There are compiler extensions, however, and apparently C++14 includes the 0b prefix for binary. (Note that this answer was originally posted in 2010.)

    One popular workaround is to include a header file with helper macros. One easy option is also to generate a file that includes macro definitions for all 8-bit patterns, e.g.:

    #define B00000000 0
    #define B00000001 1
    #define B00000010 2
    …
    

    This results in only 256 #defines, and if larger than 8-bit binary constants are needed, these definitions can be combined with shifts and ORs, possibly with helper macros (e.g., BIN16(B00000001,B00001010)). (Having individual macros for every 16-bit, let alone 32-bit, value is not plausible.)

    Of course the downside is that this syntax requires writing all the leading zeroes, but this may also make it clearer for uses like setting bit flags and contents of hardware registers. For a function-like macro resulting in a syntax without this property, see bithacks.h linked above.

提交回复
热议问题