Xeno
Xeno

Reputation: 11

Trouble understanding piece of code. Bitwise operations in c

I have the following segment of code and am having trouble deciphering what it does.

/* assume 0 <= n <=3 and 0 <= m <=3 */
    int n8= n <<3;
    int m8 = m <<3;
        int n_mask = 0xff << n8;
    int m_mask = 0xff << m8; // left bitshifts 255 by the value of m8
    int n_byte = ((x & n_mask) >> n8) & 0xff;
    int m_byte = ((x & m_mask) >> m8) & 0xff;
    int bytes_mask = n_mask | m_mask ;
    int leftover = x & ~bytes_mask;
    return ( leftover | (n_byte <<m8)| (m_byte << n8) );

Upvotes: 0

Views: 103

Answers (1)

user555045
user555045

Reputation: 64913

It swaps the nth and mth bytes.

The start has two parallel computations, one sequence with n and one sequence with m, that select the nth and mth byte like this:

Step 1: 0xff << n8

0x000000ff <<  0 = 0x000000ff
           ..  8 = 0x0000ff00
           .. 16 = 0x00ff0000
           .. 24 = 0xff000000

Step 2: x & n_mask

x = 0xDDCCBBAA

x & 0x000000ff = 0x000000AA
x & 0x0000ff00 = 0x0000BB00
x & 0x00ff0000 = 0x00CC0000
x & 0xff000000 = 0xDD000000

Step 3: ((x & n_mask) >> n8) & 0xff (note: & 0xff is required because the right shift is likely to be an arithmetic right shift, it would not be required if the code worked with unsigned integers)

n = 0: 0x000000AA
    1: 0x000000BB
    2: 0x000000CC
    3: 0x000000DD

So it extracts the nth byte and puts it at the bottom of the integer.

The same thing is done for m.

leftover is the other (2 or 3) bytes, the ones not extracted by the previous process. There may be 3 bytes left over, because n and m can be the same.

Finally the last step is to put it all back together, but with the byte extracted from the nth position shifted to the mth position, and the mth byte shifted to the nth position, so they switch places.

Upvotes: 2

Related Questions