Geo*_*iuc 1 java bits bit-manipulation xor
int a= 21;//10101
int b = 269;//100001101
Run Code Online (Sandbox Code Playgroud)
a^b 会做
10101
100001101
---------
100011000
Run Code Online (Sandbox Code Playgroud)
但我想做
10101
100001101
---------
001011101
Run Code Online (Sandbox Code Playgroud)
有没有办法在不改变原始数字的情况下做到这一点?
您可以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
Run Code Online (Sandbox Code Playgroud)