Reverse and Bitwise

Here is the 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 the variable a and b that I have to send to this function in order to solve the output value of d?

In other words, how can I cancel the algorithm to say if I want d = 11?

+3
source share
3 answers

It:

while(c) {
    c &= c - 1;
    d++;
}

counts the number of 1 bits per c. For example, if c = 10110, d will be 3.

It:

c = a ^ b;

a b. , 1-, a, b, , , a b, 1. :

101110 ^
011010
========
110100

, 1 a ^ b. , a = 0, b = number with d 1-bits.

d 1-, b = (2 to the power of d) - 1.

, d = 11, a = 0 b = (2 to the power of 11) - 1 = 2048 - 1 = 2047.

2 , :

2 to the power of k == 1 << k

, : encryption(a, b) == d if a = 0 and b = (1 << d) - 1.

+1

d - "1" c, . http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan.

a b, - XOR 11 , . a = 0 b = 2047.

( . . ().)

+1

I see that it counts SET bits in XOR b?

Ok, then let's say a == 0, b == 4095.

-1
source

Source: https://habr.com/ru/post/1740563/


All Articles