Byte Swapping Program help

Neeraj Sharma

Neeraj Sharma

@neeraj-iAaNcG Oct 23, 2024
Okay so this program was asked from me in an interview and in spite of answering all the previous questions I couldn't clear it because I could not write this program.

Question: Consider a 32-bit machine where integer variable is of 4 bytes
|b1|b2|b3|b4|
Write a C program to swap b1 and b2 and swap b3 and b4. b1,b2,b3,b4 are byte 1, byte 2 and so on.

I proposed a method to convert the integer in binary format and then divide the binary format in 4 arrays of size 8 each and then rearrange them so that the bytes are swapped. But it was a lengthy program and he told me to write this program using Union and I couldn't. So please help me with this.

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • silverscorpion

    silverscorpion

    @silverscorpion-iJKtdQ Mar 16, 2012

    well, you can just use bitshift operator to split the bytes.. Like this:
    Let's say you have the integer stored in a variable a.

    b = a>>8; c = a<<8
    a = b & c
    
    And that's it. Note that these are bitwise operators which operate on individual bits in the integer. The operators and how you use them differs based on the programming language.
  • Neeraj Sharma

    Neeraj Sharma

    @neeraj-iAaNcG Mar 16, 2012

    Thanks,but he told me to do it using Unions using some kind of character buffer which confused me and I am still not able to crack this problem