# How to invert boolean byte coding function?

I've got simple byte coding function:

y = x and E0 or x and 1F xor 05

Now I want to express x = ...? Is it possible using Mathematica (for more complex ones), please? TIA

x = y and 05 or y and FA

Could do this by expanding into explicit bit lists and solving mod 2.

Set up variables:

byteLen = 8;
xbits = Array[x, byteLen];
ybits = Array[y, byteLen];


Provide constants:

c1 = 16^^E0;
c2 = 16^^1F;
c3 = 16^^05;


Code to convert numbers to bit lists and code to rewrite bitwise logical operations as arithmetic ops.

numberToBits[num_] := IntegerDigits[num, 2, byteLen]

and[a_, b_] := a*b
or[a_, b_] := a + b + a*b
xor[a_, b_] := a + b


Here is the example in question. The precedence of xor was not obvious to me so I took a guess. I use Solve to do the work.

Solve[
ybits == or[and[xbits, numberToBits[c1]],
xor[and[xbits, numberToBits[c2]], numberToBits[c3]]], xbits,
Modulus -> 2]

(* Out[121]= {{x[1] ->
ConditionalExpression[C[8],
y[1] == C[8] && y[2] == C[7] && y[3] == C[6] && y[4] == C[5] &&
y[5] == C[4] && y[6] == 1 + C[3] && y[7] == C[2] &&
y[8] == 1 + C[1]],
x[2] -> ConditionalExpression[C[7],
y[1] == C[8] && y[2] == C[7] && y[3] == C[6] && y[4] == C[5] &&
y[5] == C[4] && y[6] == 1 + C[3] && y[7] == C[2] &&
y[8] == 1 + C[1]],
x[3] -> ConditionalExpression[C[6],
y[1] == C[8] && y[2] == C[7] && y[3] == C[6] && y[4] == C[5] &&
y[5] == C[4] && y[6] == 1 + C[3] && y[7] == C[2] &&
y[8] == 1 + C[1]],
x[4] -> ConditionalExpression[C[5],
y[1] == C[8] && y[2] == C[7] && y[3] == C[6] && y[4] == C[5] &&
y[5] == C[4] && y[6] == 1 + C[3] && y[7] == C[2] &&
y[8] == 1 + C[1]],
x[5] -> ConditionalExpression[C[4],
y[1] == C[8] && y[2] == C[7] && y[3] == C[6] && y[4] == C[5] &&
y[5] == C[4] && y[6] == 1 + C[3] && y[7] == C[2] &&
y[8] == 1 + C[1]],
x[6] -> ConditionalExpression[C[3],
y[1] == C[8] && y[2] == C[7] && y[3] == C[6] && y[4] == C[5] &&
y[5] == C[4] && y[6] == 1 + C[3] && y[7] == C[2] &&
y[8] == 1 + C[1]],
x[7] -> ConditionalExpression[C[2],
y[1] == C[8] && y[2] == C[7] && y[3] == C[6] && y[4] == C[5] &&
y[5] == C[4] && y[6] == 1 + C[3] && y[7] == C[2] &&
y[8] == 1 + C[1]],
x[8] -> ConditionalExpression[C[1],
y[1] == C[8] && y[2] == C[7] && y[3] == C[6] && y[4] == C[5] &&
y[5] == C[4] && y[6] == 1 + C[3] && y[7] == C[2] &&
y[8] == 1 + C[1]]}} *)


Offhand I'm not sure how to get the solution nicely parametrized in terms of the y variables. One can do this by omitting the Modulus->2 setting to Solve, but I doubt this is a generally safe approach.