Nibble_Swap or Swapping 0x1234

208 views Asked by At

The Input is 0x1234 and I want the output as 0x2143 but I am getting 0x4321

#include <stdio.h>

#define SWAP(num) (((num) & 0x0F) << 4) | (((num) & 0xF0) >> 4)

int main() {
    short input = 0x1234;
    short output = SWAP(input);
    
    print("Input: 0x%04X\n", input);
    print("Output: 0x%04X\n", output);
    
    return 0;
}
2

There are 2 answers

0
Nierusek On

You're not getting 0x4321, but 0x0043. You forgot about the higher byte and you wrote print instead of printf. Code below does what you want.

#include <stdio.h>

#define SWAP(num) (((num) & 0x0F00) << 4) | (((num) & 0xF000) >> 4) | \
    (((num) & 0x0F) << 4) | (((num) & 0xF0) >> 4)

int main() {
    short input = 0x1234;
    short output = SWAP(input);
    
    printf("Input: 0x%04X\n", input);
    printf("Output: 0x%04X\n", output);
    
    return 0;
}
0
Vlad from Moscow On

This macro

#define SWAP(num) (((num) & 0x0F) << 4) | (((num) & 0xF0) >> 4)

swaps only two nibbles of the less significant byte.

So the result will be

0x43

If you want to get the output

0x2143

you need to write

#include <stdio.h>

#define SWAP(num) ( ( ( num ) & 0xF000u ) >> 4 | ( ( num ) & 0x0F00u ) << 4 |\
( ( num ) & 0xF0u ) >> 4 | ( ( num ) & 0x0Fu ) << 4 )

int main( void )
{
    short input = 0x1234;
    short output = SWAP( input );

    printf( "%#x\n", output );
}