XOR problem with two binary numbers

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

I put the numbers in int j and go through a loop to reach each one. Below is my line of code.

j2 = j^(binaryToDecimal(0110));

      

However, I cannot 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:

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;
}

      

+3


source to share


3 answers


The problem with your code is that when you pass "0110" as an argument, the compiler treats it as an octal number, that is, 0110 ==> 72 (decimal).



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

+4


source


In C, any "number" prefixed with c 0

will be interpreted as octal.

Common numeric prefixes are:

  • 0b10110

    - specify binary file (base 2) with prefix 0b

    - only supported by some C compilers
  • 026

    - specify octal (base 8) with prefix 0

  • 22

    - indicate decimal (base 10) with the prefix "no"
  • 0x16

    - specify hexadecimal (base 16) with prefix 0x

All of the above examples are equal ( 22

decimal / base 10).

Most likely my preferred approach would be for you to be comfortable with hex. This will completely remove your dependency on the "convert binary to x" function, as well as any implementation errors in that function.



Try:

j2 = j ^ 0x06;

      

Or (if your compiler supports it):

j2 = j ^ 0b0110;

      

It's clear, concise and accurate.

0


source


As already said, 0110

is an octal number, so binaryToDecimal(0110)

will not work. You can use a similar syntax to express the number you wanted (as long as you use a compiler that supports C ++ 14 or better) with 0b0110

. This probably expresses what you mean more clearly than binaryToDecimal(110)

.

With this, your first line will be written as

j2 = j^0b0110;

      

0


source







All Articles