Raycherr
Raycherr

Reputation: 253

Trouble with XOR of two binary numbers

I have a list of numbers from 0 to 16 and I want to XOR their binary form with 0110.

I have place the numbers in int j and will go through a loop to reach each of them. The following is my line of code.

j2 = j^(binaryToDecimal(0110));

However, I am unable to get the results I want. For example 0 XOR 0110 gave me a result of 16 instead of 0110B = 6. What am I missing here?

Here's my binary to decimal code if needed:

long binaryToDecimal(long n) {
int remainder;
    long decimal = 0, i=0;
    while(n != 0) {
        remainder = n%10;
        n = n/10;
        decimal = decimal + (remainder*pow(2,i));
        ++i;
    }
    return decimal;
}

Upvotes: 3

Views: 422

Answers (3)

Attie
Attie

Reputation: 6979

In C any 'number' that is prefixed with a 0 will be interpreted as octal.

Here are the common numeric prefixes:

  • 0b10110 - Specify binary (base 2) with the 0b prefix - only supported by some C compilers
  • 026 - Specify octal (base 8) with the 0 prefix
  • 22 - Specify decimal (base 10) with 'no' prefix
  • 0x16 - Specify hexadecimal (base 16) with the 0x prefix

All of the examples above are equal (22 in decimal / base 10).

By far my preferred approach would be for you to get comfortable with hexadecimal. That would entirely remove your dependency on a function to 'convert binary to x', as well as any implementation errors in that function.

Try:

j2 = j ^ 0x06;

Or (if your compiler supports it):

j2 = j ^ 0b0110;

This is clear, concise and to the point.

Upvotes: 0

Peter G
Peter G

Reputation: 2821

As already covered, 0110 is an octal number so binaryToDecimal(0110) won't work. You can use similar syntax to express the number you wanted to (as long as you're using a compiler that supports C++14 or better) with 0b0110. This probably more clearly expresses what you meant compared to binaryToDecimal(110).

With this, your first line would be written as

j2 = j^0b0110;

Upvotes: 0

Parvinder Singh
Parvinder Singh

Reputation: 74

The problem with your code is that when you pass "0110" as an argument then compiler treat it as an octal number i.e. 0110 ==> 72 (decimal).

Instead, pass "110" as in argument. Yo will get the expected result.

Upvotes: 4

Related Questions