LearnFrenzy
Sign in Take a free test

Bitwise Operators · Bit Manipulation Programs · Question 2

Swap the two nibbles of a byte in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Swap the high and low 4 bits of a byte, e.g. 0xAB becomes 0xBA.

Solution
main.c
#include <stdint.h>
#include <stdio.h>

uint8_t swap_nibbles(uint8_t b) {
    return (uint8_t) (((b & 0x0Fu) << 4) | ((b & 0xF0u) >> 4));
}

int main(void) {
    printf("0x%02X 0x%02X %u\n", swap_nibbles(0xAB), swap_nibbles(0x12), swap_nibbles(100));
    return 0;
}

Output Verified by compiling and running

0xBA 0x21 70

Move the low nibble up by 4, the high nibble down by 4, and OR them. 100 is 0x64, which becomes 0x46 = 70. The final cast keeps the result in 8 bits.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links