Question

I got an assignment today at my faculty (Mathematics Faculty of Belgrade, Serbia) which says:

1) Write a program that for two given integers x and y, inverts in integer x those bits that match the corresponding bits in y, while the rest of the bits remain the same.

For example:

x  = 1001110110101
y  = 1100010100011
x' = 0011101011100

I managed to write a program that does that, but I am a little insecure about the quality of my solution. Please, if you have time, check out the code and tell me how I could improve it.

int x, y, bitnum;
int z = 0;
unsigned int mask;

bitnum = sizeof(int) * 8;
mask = 1 << bitnum - 1;

printf("Unesi x i y: ");
scanf("%d%d", &x, &y);

while (mask > 1) {
    if ( (((x & mask) == 0) && ((y & mask) == 0)) ||
          ((x & mask) && ((y & mask) == 0)) )
        z += 1;                                   
    z <<= 1;
    mask >>= 1;
} /* <-- THAT'S HOW STUPID PEOPLE SOLVE PROBLEMS... WITH HAMMER! */
z = y~; /* <-- THAT'S HOW SMART PEOPLE SOLVE PROBLEMS... WITH ONE LINE */

Everything works correctly, for x = 423 and y = 324 for example, I get z = -344, which is correct. Also, bit prints match I would just like to know if there is a better way to do this.

Thanks.

Was it helpful?

Solution

If you take a look at your x/y/x' example, it must strike you that x' is a complement to y. And indeed it's like that.

 x  y  x'
 --------
 1  1  0
 0  0  1
 1  0  1
 0  1  0

Spoiler (hover your mouse over block below, if you want to see a solution):

For bits that match, you invert bit in x, but as it is the same as bit in y, it's the same as inverting bit in y. When they do not match, you keep the bit from x, what is already inversion of bit in y on its own. I hope you can see the one-line solution already yourself: x' = ~y;

OTHER TIPS

//Try with the next code:

unsigned int mask1, mask2, mask3, answ;

mask1 = x & y; // identify bits with 1 that match

mask2 = ~x & ~y; // identify bits with 0 that match

mask3 = mask1 | mask2; // identify bits with 0 or 1 that match

answ = x ^ m3; // Change identified bits

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top