Search code examples
javabit-manipulationxorbit

Xor starting with the significant bit


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?


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