The C prefix for binary constants (0b)

From Stm32World Wiki
Jump to navigation Jump to search

Developing simple programs for our STM32 Tutorial Videos we have often used the '0b' prefix to write binary constants, for example:

uint8_t something = 0b10101010;

When developing code for embedded systems, this is a particularly convenient feature. In datasheets for various peripherals, one will often come across specifications like this (from the CS43L22 datasheet):

Bit example.png

In this example a few macros like:

#define CC43L22_INT_CTL_1_DACDIF_SOMETHING      0b00000100
#define CC43L22 INT_CTL_1_DACDIF SOMETHING_ELSE 0b00001000

Would obviously make it a lot easier to relate to the datasheet.

Unfortunately, when reading the C "bible" Kernighan & Ritchie: The C Programming Language (2nd Edition, Only the 0 (for octal) or 0x (for hex) prefixes are defined. The big question is therefore, is it safe to use this prefix or should it be avoided completely. As it turns out (described in research paper linked below) it IS probably safe to use. The feature is defined in a very recent addition to the C standard (C23) but it has been supported by both CLANG and GNU GCC since 2008.

Video

Miscellaneous Links