#I need help understanding how to byteSwap using bitwise operators in C

10 messages · Page 1 of 1 (latest)

tepid veldt
#

This is my problem:

  • 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

i need help understanding how it works and how I can get it to work

royal sable
#

looks like it works by swapping the nth and mth bytes

tepid veldt
#

how can i swap them by shifting the nth and mth?

royal sable
#

what have you tried?

tepid veldt
#

what would this line do?

#

int byteSwap(int x, int n, int m) {
int swap = (x>>(n-1) & 0x1) ^ ((x>>(m-1) & 0x1);//extraction of the byte at n and m position based on the value of x
x = x^(swap << (n-1));// first swap places n where m position
x = x^(swap << (m-1));// second swap places m where n position
return x;

royal sable
#

0x1 is only going to be extracting a single bit, not a byte

tepid veldt
#

so what if I used like 0xFF

royal sable
#

that's a step in the right direction

#

you'll also need to adjust n and m, since shifting by 3 means 3 bits, not 3 bytes