so we need to write a method
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: ! ~ & ^ | + << >>
also we cannot use loops/recursion
but my following code fails with this test case :
Test byteSwap(-2147483648[0x80000000],0[0x0],3[0x3]) failed…
…Gives -128[0xffffff80]. Should be 128[0x80]
not sure why though this is my code so far
int byteSwap(int x, int n, int m) {
int nBitShift = n << 3;
int mBitShift = m << 3;
int nByte = x & (0xFF << nBitShift); //gets the byte at position n
int mByte = x & (0XFF << mBitShift); //gets the byte at position m
int newX = x + ~(nByte + mByte) + 1; //make 0's in the nth and mth byte
nByte = nByte >> nBitShift; //shift back
nByte = nByte << mBitShift; //shift to the mth spot
mByte = mByte >> mBitShift; //shift back
mByte = mByte << nBitShift; //shift to the nth spot
return nByte + mByte + newX;
}
edit:yes this is hw, but i need help
Arithmetic shift of a signed value sign-extends the operand. If you switch the type of your temporary variables to
unsigned, your solution would avoid this problem.