我有一個用 JS 撰寫的將x、y、z決議為 1 個數字的代碼。
是否有可能僅通過知道最終數字和對其進行的操作來以某種方式恢復操作并回傳x,y,z ?我在 rever 函式中對x,y,z進行了硬編碼, 以測驗反向程序并且它可以作業。但我需要的是從 parsedOutput 中取回x,y,z
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
uj5u.com熱心網友回復:
如果您將整數與整數異或兩次,您將得到原始數字
(a ^ b) ^ b = a
異或運算的順序無關緊要
a ^ b ^ c = b ^ a ^ c
所以如果你有
a ^ c0 ^ c1 ^ c2 = b
然后
a = b ^ c0 ^ c1 ^ c2
所以答案是肯定的,您只需以相反的順序 xor 即可獲得子結果......或者如果您只想要原始值,可以按任何順序。
所以你有了:
w0 = 0;
w1 = w0 ^ (x << 9);
w2 = w1 ^ (y << 5);
w3 = w2 ^ (z );
我會這樣反轉它:
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508255.html
標籤:javascript 异或
上一篇:為下拉選單選擇添加占位符照片