Following up on the previous episode (BIVBlog #46: Bitwise Operators in C (not only) for Microcontrollers) I explain ways to minimize the pain involved with the bitwise operators in C. While none of the shown approaches are perfect, and some are plain counterproductive, there are ways to keep your code easy to understand, modify, debug and maintain.
The alternatives range from preprocessor macros to inline functions, C++ function templates and the little known and even less understood C language bit fields to simple but application specific preprocessor macros (or inline functions, again).
Some of these ideas at first glance appear inefficient and as such ill-suited especially for microcontroller programming, but turn out to be easily optimized away again by any reasonable compiler, so I at least mention some basics on what compilers can and will do with the code variants shown.
The key idea however is to abstract away from the bit fiddling and provide a clean abstraction that localizes the underlying details and hides them from the rest of the code—in other words, a concept completely unheard of in programming…
Table of Contents
00:01:00 Different representations of bit masks, and what a compiler does with them
00:05:10 Using preprocessor macros to make bit operations more readable
00:08:30 Using regular or inline functions instead of macros
00:12:55 Using C++ function templates to support various variable types
00:15:55 C language bit fields
00:17:50 … and why not to combine them with
00:20:50 Using C++ classes for a really tight abstraction—and why it is too soon to try that
00:23:35 Using preprocessor macros for a specific application
The previous episode: BIVBlog #46: Bitwise Operators in C (not only) for Microcontrollers.