int a= 21;//10101
int b = 269;//100001101
a^b
就可以了
10101
100001101
---------
100011000
但我想做
10101
100001101
---------
001011101
有什么办法可以做到不改变原来的数字吗?
最佳答案
您可以移动 a
使其与左侧的 b
对齐。下面的示例代码适用于您的示例,但不能正确处理溢出等。不过它应该为您提供一个起点。
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
关于java - Xor 从有效位开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22540607/