Michael
Michael

Reputation: 5335

Moving and flipping bits

I need to transform an input number by bit manipulation. Here are the rules:

Here is a translation table:

Input  Input (bin)  Output  Output (bin)
0      0000         11      1011
1      0001         3       0011
2      0010         15      1111
3      0011         7       0111
4      0100         9       1001
5      0101         1       0001
6      0110         13      1101
................................

Here is what I tried:

def tr(n):
    return ((n & 1 ^ 1) << 1) | ((n >> 1 & 1) << 2) | \
    ((n >> 2 & 1 ^ 1) << 3) | 1

tr(0) gives the right number: 11, but tr(1) gives me 9. I sit here for 3 hours with headache and can't understand what is wrong. Sorry if this is something trivial or here is some stupid error. Please help.

Upvotes: 2

Views: 82

Answers (2)

Alain Merigot
Alain Merigot

Reputation: 11537

According to your specs

bit 1 should be the flipped bit 2 of input;

bit 2 should be the bit 1 of input;

bit 3 should be the flipped bit 0 of input.

your code should be

def tr(n):
  return (((n & 4) ^ 4) >> 1) | ((n & 2) << 1) |
  ((n & 1 ^ 1) << 3) | 1

Upvotes: 0

T.Lucas
T.Lucas

Reputation: 848

The following is giving the corresponding result of your translation table:

def tr(n):
    return 1 | ((n&4)>>1) ^ 2 | (n&2) << 1 | ((n&1) << 3) ^ 8

For a better understanding:

  1. bit 0 should be 1 -> 1

  2. bit 1 should be the flipped bit 2 of input. First select bit 2: n&4 then move it from bit 2 to bit 1: (n&4)>>1 finally flip the value of the bit 1 (2**1=2): ((n&4)>>1) ^ 2.

  3. bit 2 should be the bit 1 of input. First select the bit 1: n&1 then move it from bit 1 to bit 2: (n&2) << 1

  4. bit 3 should be the flipped bit 0 of input. First select the bit 0: n&1 then move it from bit 0 to bit 3: (n&1) << 3 finally flip the value of the bit 3 (2**3=8): ((n&1) << 3) ^ 8

Upvotes: 1

Related Questions