Wednesday, 15 October 2025

32-bit Bitwork: Extract Even Bits, Set UART Baud, Big-Endian Bytes

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.

#include <stdint.h> static inline uint32_t extract_even_bits(uint32_t reg){ uint32_t out = 0; unsigned k = 0; for (unsigned i = 0; i < 32; i += 2) out |= ((reg >> i) & 1u) << k++; return out; } // Examples: 0b01010101 → 0b1111, 0b10101010 → 0b0000

🔧 Set UART Baud Field (bits 8..11)

Update just the 4-bit baud field; leave everything else unchanged.

#include <stdint.h> static inline uint32_t set_baud_rate(uint32_t reg, uint8_t baud){ uint32_t m = (uint32_t)0xFu << 8; return (reg & ~m) | (((uint32_t)baud & 0xFu) << 8); } // Example: reg=0x00000000, baud=0b1010 → 0x00000A00

📦 Convert 32-bit to Big-Endian Bytes

Store MSB first for wire protocols.

#include <stdint.h> static inline void to_big_endian(uint32_t v, uint8_t b[4]){ b[0]=(uint8_t)(v>>24); b[1]=(uint8_t)(v>>16); b[2]=(uint8_t)(v>>8); b[3]=(uint8_t)v; } // Example: 0x12345678 → {0x12,0x34,0x56,0x78}

⚡ 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 volatile and 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