ATT
ATT

Reputation: 1081

Is it possible to reverse final single number output of multiple XOR and bits shifting operations

I have a code written in JS of parsing x,y,z into 1 number.

Is it possible to somehow revert the operation and get x,y,z back by only knowing the final number and the operations made on it? I have hardcoded x,y,z in the rever function in order to test the reverse process and it works. But what I need is getting the x,y,z back from the parsedOutput

let ParseWithXor = () => {
  let x = 25;
  let y = 8;
  let z = 110;
  let finalOutput = 0;
  finalOutput = finalOutput ^ (x << 9);
  console.log(` finalOutput ^ (${x} << 9) = ${finalOutput}`);
  finalOutput = finalOutput ^ (y << 5);
  console.log(` finalOutput ^ (${y} << 5) = ${finalOutput}`);
  finalOutput = finalOutput ^ z;
  console.log(`finalOutput ^ ${z} = ${finalOutput}`);
  return finalOutput;
};

let Revert = (parsedOutput) => {
  console.log(parsedOutput);
  parsedOutput = parsedOutput ^ 110;
  console.log(parsedOutput);
  parsedOutput = parsedOutput ^ (8 << 5);
  console.log(parsedOutput);
  parsedOutput = parsedOutput ^ (25 << 9);
  console.log(parsedOutput);
};

ParseWithXor();
console.log("-------------------------------------");
Revert(13166);


finalOutput ^ (25 << 9) = 12800
finalOutput ^ (8 << 5) = 13056
finalOutput ^ 110 = 13166
--------------------------------------
13166
13056
12800
0

Upvotes: 2

Views: 368

Answers (1)

Spektre
Spektre

Reputation: 51845

if you xor an integer with integer twice you will get original number

(a ^ b) ^ b = a

it does not matter the order of xor operations

a ^ b ^ c  = b ^ a ^ c

so if you have

a ^ c0 ^ c1 ^ c2 = b

then

a = b ^ c0 ^ c1 ^ c2

so the answer is yes you just xor back in reverse order to obtain the sub results... or in any order if you want just original value.

so you have:

w0 = 0;
w1 = w0 ^ (x << 9);
w2 = w1 ^ (y << 5);
w3 = w2 ^ (z     );

I would revers it like this:

w3 = ...;

// x,y,z from w(i)   |   w(i) from x,y,z
// ---------------------------------------
z = (w3 ^ w2);       |  w2 = w3 ^ (z     ); 
y = (w2 ^ w1) >> 5;  |  w1 = w2 ^ (y << 5); 
x = (w1 ^ w0) >> 9;  |  w0 = w1 ^ (x << 9); 

// x,y,z from w3,w0 but x,y,z must not overlap bits
// z = <0,31> 
// y = <0,15>
// x = <0,(max/512)-1> 
// ----------------------------------------------
w = w0 ^ w3;
z = w & 31; w >>= 5;
y = w & 15; w >>= 4;
x = w;

Upvotes: 1

Related Questions