Here’s the following algorithm:
int encryption(int a, int b) {
short int c, c2;
uint8_t d;
c = a ^ b;
c2 = c;
d = 0;
while(c) {
c &= c - 1;
d++;
}
return d;
}
How can I find which variable a and b I should send in that function to decide of the output value of d?
In other words, how can I reverse the algoritm to let’s say if I want d=11?
This:
counts the number of 1-bits in
c. So for example, ifc = 10110, d will be 3.This:
Does an exclusive or between
aandb. This means that all the 1-bits that share the same position in bothaandbwill be zeroes, and all the positions that have different values inaandbwill become 1. For example:So basically, the algorithm finds the number of 1-bits in
a ^ b. To force it to output a certain value, just makea = 0thenb = number with d 1-bits.To get a number with
d1-bits, considerb = (2 to the power of d) - 1.So if you want
d = 11, thena = 0andb = (2 to the power of 11) - 1 = 2048 - 1 = 2047.To efficiently compute 2 to a certain power programmatically, use this formula:
2 to the power of k == 1 << kSo, basically:
encryption(a, b) == d if a = 0 and b = (1 << d) - 1.