Question

int a= 21;//10101
int b = 269;//100001101

a^b will do

    10101
100001101
---------
100011000

but I want to do

10101
100001101
---------
001011101

Is there any way to do it without changing the original numbers?

Was it helpful?

Solution

You can shift a to align it with b on the left. The sample code below works with your example but does not properly handle overflows etc. It should give you a starting point though.

int a = 21;
int b = 269;

int shift = Integer.numberOfLeadingZeros(a) - Integer.numberOfLeadingZeros(b);

int c = (a << shift) ^ b;
System.out.println(Integer.toBinaryString(c)); // 1011101

OTHER TIPS

You could use a left bit shift on a, which will add 0s to the end of a, which won't change the value of your XOR:

//Calculate how far to shift
int shiftLength = Integer.toBinaryString(b).length() - Integer.toBinaryString(a).length();

//Apply shift
int aShited = a << shiftLength;

//Execute
System.out.println(Integer.toBinaryString(aShifted^b));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top