Tiny, safe helpers you’ll use everywhere. 0-based indexing; LSB = 0. Keep them static inline in a header for zero-overhead reuse.
✅ Extract Even Bits (0,2,4,…,30) → packed
Compress even-positioned bits into consecutive bits (LSB-first). Result fits in 16 bits.
🔧 Set UART Baud Field (bits 8..11)
Update just the 4-bit baud field; leave everything else unchanged.
📦 Convert 32-bit to Big-Endian Bytes
Store MSB first for wire protocols.
⚡ Pro Tips
-
Use unsigned shifts (
1u,uint32_t) to avoid UB. -
Even-bit extract yields at most 16 bits → you can cast to
uint16_t. -
For HW registers, use
volatileand guard shared sinks (UART/ITM) with a mutex.
🎯 Conclusion
Three drop-ins: slice even bits, tweak a 4-bit field, and serialize to network order—clean, predictable, portable.
Written By: Musaab Taha
This article was improved with the assistance of AI.
No comments:
Post a Comment