-1

Hello beautiful people, I need a help with output of this program:

#include <stdio.h>

int main() {
    int x,y;
    scanf("%d %d",&x,&y);
    int t = x^y;
    int p = 0;
    while (t > 0) {
        p += t%2;
        t /= 2;
    }
    printf("%d", p);
    return 0;
}

I tried to write it down on paper and do some work by hand. So i wrote this :

lets say for x = 2 and y = 4

  1. first iteration:

    p = 0 + 16mod2 which is equal to 0

    t = 8

  2. second iteration:

    p = 0 + 8mod2 which is equal to 0

    t = 4

  3. third iteration:

    p = 0 + 4mod2 which is equal to 0

    t = 2

  4. forth iteration:

    p = 0 + 2mod2 which is equal to 0

    t = 1

And output should be 0, but somehow when I run code I get 2. Can someone help me out with this one please? And are there any other cases to consider, like what if x = 0, y = 0 or x and y are < 0 ?

  • 1
    Hamming distance? – EOF May 19 '17 at 19:22
  • @EOF it is indeed hamming distance – รยקคгรђשค May 19 '17 at 19:24
  • 1
    `x^y` is an exclusive OR on x and y, not x to the power of y. – Gavin May 19 '17 at 19:24
  • Bit operations are technically only defined for `unsigned` types. Better to use an exact unsigned type, e.g. `#include ` and then `uint32_t` instead of `int`, or at least `unsigned` instead of `int` – David C. Rankin May 19 '17 at 19:30
  • @DavidC.Rankin From where do you get bit operations only being defined for unsigned types? They *might* only be defined for *non-negative* **values**, but that is not the same at all. – EOF May 19 '17 at 19:34
  • @DavidC.Rankin: Can you please provide a reference to the standard supporting your statement? – too honest for this site May 19 '17 at 19:43
  • [**Are the results of bitwise operations on signed integers defined?**](http://stackoverflow.com/questions/11644362/are-the-results-of-bitwise-operations-on-signed-integers-defined) – David C. Rankin May 19 '17 at 19:45
  • OK, the artful explanation is `non-negative` instead of `unsigned` point well taken. (I guess that begs the question -- *"How to easily protect against non-negative entry from a type-safety standpoint?*"). – David C. Rankin May 19 '17 at 19:46

3 Answers3

2

The problem here, is that you assume that 2^4 == 16, when in fact, it is only 6, as the ^ operator, is actually an XOR.

You should be using

int t = pow(x, y)
Matt Clark
  • 27,671
  • 19
  • 68
  • 123
  • use pow(x,y) instead – yar May 19 '17 at 19:26
  • Simple mistake for somebody learning, as the carrot generally represents exponents in math ;) Be sure to include `math.h` to have access to this method. Good luck and happy coding! – Matt Clark May 19 '17 at 19:30
0
 int t = x^y;

Is not "x raised to the power of y". It's "x XOR y". T starts at 6 in your example.

James Curran
  • 101,701
  • 37
  • 181
  • 258
0

As others have mentioned x^y is XOR operation, what you had in mind is :

#include <math.h>
....
int t = pow(x,y);
d9ngle
  • 1,303
  • 3
  • 13
  • 30