View Feed
Coffee Room
Discuss anything here - everything that you wish to discuss with fellow engineers.
12832 Members
Join this group to post and comment.

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
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.
silverscorpion • Mar 17, 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.
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

Share this content on your social channels -