Reputation: 4633
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?
Upvotes: 1
Views: 62
Reputation: 18167
You could use a left bit shift on a
, which will add 0
s 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));
Upvotes: 1
Reputation: 328598
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
Upvotes: 5