Byte Swapping Program help

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

  • silverscorpion
    silverscorpion
    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
    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

You are reading an archived discussion.

Related Posts

Hey all, Do any of you have FlashLite enabled phones like Samsung STAR, Samsung MONTE, Samsung CORBY? Have you ever tried writing codes for it? Have you tried developing custom...
When searched for this doubt, I found different answers.Got very confused.Someone help to find correct. The answers which I found for this are 1) Due to: average voltage generated by...
Charge Your Smartphone With The Power Of Your Breath ​ ​​ ​Charge Your Smartphone With The Power Of Your Breath..The AIRE mask is a concept that hails from the mind...
Current technology can make virtual dressing rooms a reality. One can try different out fits on images in a mirror without hiding in a cramped trial cubicle without the hassle...
Everyone knows that the whole education section in India and if I'm right; in the world world, has become a pure business where more importance is given to picking out...