The C prefix for binary constants (0b)

From Stm32World Wiki
Jump to navigation Jump to search

When looking at STM32 code examples, one often come across binary values prefixed with '0b', for example '0b10101010'. What is odd is that this prefix is not really mentioned in the C standards, including the K&R C specification. In this article we will be looking at why this is.

Video

We have created a video covering the topic of this article. Watch it on Youtube here:

Examples

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.

The standards

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.

GCC has supported the feature since around 2008 and it was included in the C++14 standard, however, it was only included in C in C23.

As it turns out (described in research paper linked below) it IS probably safe to use.

Miscellaneous Links