In: Computer Science
C code required
* byteSwap - swaps the nth byte and the mth byte
* Examples: byteSwap(0x12345678, 1, 3) = 0x56341278
* byteSwap(0xDEADBEEF, 0, 2) = 0xDEEFBEAD
* You may assume that 0 <= n <= 3, 0 <= m <= 3
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 25
* Rating: 2
*/
#include <stdio.h> int byteSwap(int x, int n, int m) { // offset is simply bitPosition for bytes.. // So byte 1 means bit position 8. int nOffset = n << 3; int mOffset = m << 3; int nthByte = ((x & (0xFF << nOffset) ) >> nOffset) & 0xFF; int mthByte = ((x & (0xFF << mOffset) ) >> mOffset) & 0xFF; int i = nthByte << mOffset; int j = mthByte << nOffset; // reset nTh & mthByte. x &= ~((0xFF << nOffset) | (0xFF << mOffset)); // at last join the reseted value with mth and nTh bytes int ans = x | i | j; return ans; } int main(void) { printf("%0X\n", byteSwap(0x12345678, 1, 3)); printf("%0X\n", byteSwap(0xDEADBEEF, 0, 2)); return 0; }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.