To swap the first and third bytes in a uint32_t value, we can use a combination of bitwise masking, shifting, and OR operations. This method is portable and works regardless of the system's endianness.
🔍 Understanding the Problem
A uint32_t is a 32-bit unsigned integer, which means it consists of four bytes:
- Byte 0 (Most Significant): Bits 31–24
- Byte 1: Bits 23–16
- Byte 2: Bits 15–8
- Byte 3 (Least Significant): Bits 7–0
For example, the value 0x12345678 is composed of the following bytes:
| Byte Index | Hex Value |
|---|
| 0 | 0x12 |
| 1 | 0x34 |
| 2 | 0x56 |
| 3 | 0x78 |
Swapping the first (index 0) and third (index 2) bytes results in:
0x56341278
✅ The Magic Trick (Portable Solution)
Here's a concise and efficient way to perform the swap using bitwise operations:
#include <stdint.h>
uint32_t swap_first_third_byte(uint32_t x) {
return ((x & 0xFF000000) >> 16) | // Move first byte to third position
((x & 0x0000FF00) << 16) | // Move third byte to first position
(x & 0x00FF00FF); // Preserve second and fourth bytes
}
🧠 How It Works
-
Mask the First Byte:
x & 0xFF000000
This isolates the first byte (bits 31–24). Shifting it right by 16 bits places it in the third byte position (bits 15–8).
-
Mask the Third Byte:
x & 0x0000FF00
This isolates the third byte (bits 15–8). Shifting it left by 16 bits places it in the first byte position (bits 31–24).
-
Preserve the Second and Fourth Bytes:
x & 0x00FF00FF
This mask preserves the second (bits 23–16) and fourth (bits 7–0) bytes.
-
Combine All Parts:
Using the bitwise OR operator (|), we combine the three parts into the final result.
📌 Example
Let’s test with the value 0x12345678:
- First byte:
0x12 → shifted right → 0x00001200
- Third byte:
0x56 → shifted left → 0x56000000
- Preserved bytes:
0x340078 → 0x00340078
Combining:
0x56000000 | 0x00001200 | 0x00340078 = 0x56341278
Which is the expected result.
🧪 Another Example
Input: 0xAABBCCDD
- First byte:
0xAA → 0x0000AA00
- Third byte:
0xCC → 0xCC000000
- Preserved bytes:
0xBB00DD
Result:
0xCC000000 | 0x0000AA00 | 0x00BB00DD = 0xCCBBAAED
🧾 Summary
This bitwise trick is an elegant and efficient way to swap two specific bytes within a 32-bit unsigned integer. It avoids the need for casting to arrays or unions, making it portable and safe across different platforms.
🧩 Final Code
#include <stdint.h>
uint32_t swap_first_third_byte(uint32_t x) {
return ((x & 0xFF000000) >> 16) | ((x & 0x0000FF00) << 16) | (x & 0x00FF00FF);
}
This is the magic trick to swap the first and third bytes in a uint32_t. ✨