CrazyEngineers
  • Byte Swapping Program help

    Neeraj Sharma

    Member

    Updated: Oct 23, 2024
    Views: 1.0K
    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.
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • silverscorpion

    MemberMar 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.
    Are you sure? This action cannot be undone.
    Cancel
  • Neeraj Sharma

    MemberMar 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
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register