9 Essential C Code Snippets Every Embedded Engineer Should Know
This article presents a curated collection of nine high‑utility C code snippets for embedded development, covering a circular buffer, custom assertions, bit reversal, fixed‑point arithmetic, endianness conversion, bit masks, timer handling, binary search, and a simple bitset structure, each with concise explanations and ready‑to‑use implementations.
1. Circular Buffer (Ring Buffer)
Provides a FIFO queue for streams such as UART data. The implementation defines a CircularBuffer struct with a fixed‑size array, head/tail indices, and a count field. The push and pop functions handle wrap‑around.
typedef struct {
int buffer[SIZE];
int head;
int tail;
int count;
} CircularBuffer;
void push(CircularBuffer *cb, int data) {
if (cb->count < SIZE) {
cb->buffer[cb->head] = data;
cb->head = (cb->head + 1) % SIZE;
cb->count++;
}
}
int pop(CircularBuffer *cb) {
if (cb->count > 0) {
int data = cb->buffer[cb->tail];
cb->tail = (cb->tail + 1) % SIZE;
cb->count--;
return data;
}
return -1; /* empty */
}2. Assertion Macro
A custom assert that is active when NDEBUG is not defined; otherwise it expands to a no‑op.
#define assert(expr) ((void)0)
#ifndef NDEBUG
#undef assert
#define assert(expr) ((expr) ? (void)0 : assert_failed(__FILE__, __LINE__))
#endif
void assert_failed(const char *file, int line) {
printf("Assertion failed at %s:%d
", file, line);
/* optional error handling */
}3. Bit Reversal
Reverses the order of bits in an unsigned integer, useful for protocols that require bit‑wise transformations.
unsigned int reverse_bits(unsigned int num) {
unsigned int numOfBits = sizeof(num) * 8;
unsigned int reverseNum = 0;
for (unsigned int i = 0; i < numOfBits; ++i) {
if (num & (1u << i))
reverseNum |= 1u << (numOfBits - 1 - i);
}
return reverseNum;
}4. Fixed‑Point Arithmetic
Defines a 16‑bit fixed‑point type with 8 fractional bits and provides macros for conversion and a multiplication helper.
typedef int16_t fixed_t;
#define FIXED_SHIFT 8
#define FLOAT_TO_FIXED(f) ((fixed_t)((f) * (1 << FIXED_SHIFT)))
#define FIXED_TO_FLOAT(f) ((float)(f) / (1 << FIXED_SHIFT))
fixed_t fixed_multiply(fixed_t a, fixed_t b) {
return (fixed_t)(((int32_t)a * (int32_t)b) >> FIXED_SHIFT);
}5. Endianness Conversion
Swaps the high and low bytes of a 16‑bit value, enabling conversion between big‑endian and little‑endian representations.
uint16_t swap_bytes(uint16_t value) {
return (value >> 8) | (value << 8);
}6. Bit Mask Macro
Generates a mask with a single bit set, useful for flag manipulation.
#define BIT_MASK(bit) (1U << (bit))7. Timer Counting (AVR Example)
Minimal example for configuring and reading a hardware timer on AVR microcontrollers. The include directive is escaped to avoid HTML parsing.
#include <avr/io.h>
void setup_timer(void) {
/* configure prescaler, mode, etc. */
}
uint16_t read_timer(void) {
return TCNT1; /* current counter value */
}8. Binary Search
Classic binary search implementation for a sorted integer array, returning the index of the target or -1 if not found.
int binary_search(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1; /* not found */
}9. Bitset Structure
Lightweight bitset that stores up to 32 flags in a uint32_t with helpers to set and query individual bits.
#include <stdint.h>
typedef struct {
uint32_t bits;
} Bitset;
void set_bit(Bitset *bs, int bit) {
bs->bits |= (1U << bit);
}
int get_bit(const Bitset *bs, int bit) {
return (bs->bits >> bit) & 1U;
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
