DEV Community

abbazs
abbazs

Posted on • Updated on

How to swap first byte with last byte without shifting in C?

We have a hexadecimal number 0x12345678 and we need to swap it like this 0x78345612, observe first and last bytes swapped.

We can do this using byte swapping method as follows:

#include <stdio.h>

int swap_first_to_last_byte_shift_method(int num)
{
    int res;
    int b0, b1, b2, b3;
    // Left shift the last byte 24 times.
    // 1 byte = 8 bits
    // For 3 bytes it needs be shifted 8*3 = 24 times.  
    b0 = (num & 0x000000ff) << 24;
    b1 = (num & 0x00ff0000);
    b2 = (num & 0x0000ff00);
    b3 = (num & 0xff000000) >> 24;
    res = b0 | b1 | b2 | b3;
    return res;
}

int main()
{
    int num = 0x12345678;
    int res = swap_first_to_last_byte_shift_method(num);
    printf("Input  %x\n", num);
    printf("Output %x\n", res);
}

Enter fullscreen mode Exit fullscreen mode

It shall produce the output as follows:

Input  12345678
Output 78345612
Enter fullscreen mode Exit fullscreen mode

How the same can be done without using byte shift?

#include <assert.h>
#include <stdio.h>

void swap_first_to_last_memory_shift_method(void *pv, size_t n)
{
    // assert size of the input is greater than 0
    assert(n > 0);
    char *p = pv;
    // Assign the first byte to a temporary variable
    char temp = p[0];
    // Swap last to first.
    p[0] = p[n-1];
    // Swap last to the temp
    p[n-1] = temp;
}

// Macro to swap
#define SWAP_FRIST_TO_LAST(x) swap_first_to_last_memory_shift_method(&x, sizeof(x));

int main()
{
    int num = 0x12345678;
    printf("Input   %x\n", num);
    // In this method the swap at memory address level.
    // Hence no need to for additional variables.
    SWAP_FRIST_TO_LAST(num);
    printf("Output  %x\n", num);
}
Enter fullscreen mode Exit fullscreen mode

This produces the output as follows:

Input  12345678
Output 78345612
Enter fullscreen mode Exit fullscreen mode

Refrence https://stackoverflow.com/a/2182581/1437877

Top comments (0)