BigInteger类型的两个二进制数做异或操作后,希望得到的返回结果也为二进制数形式...

为什么80%的码农都做不了架构师?>>>   hot3.png

public class Test {
 public static void main(String[] args) {
  
  String thisstrhash = "0000011001111101111100101011111010000110110101110101110001100100";
  String otherstrhash = "0000011001111101101100101011111010000110110101110101111001001100";
 
  BigInteger thisintegerhash = new BigInteger(thisstrhash);
  BigInteger otherintegerhash = new BigInteger(otherstrhash);
  
  BigInteger thisintegerhash2 = new BigInteger(thisstrhash, 2);
  BigInteger otherintegerhash2 = new BigInteger(otherstrhash, 2);
  
  System.out.println(thisintegerhash);
  System.out.println(otherintegerhash);
  
  System.out.println(thisintegerhash2);
  System.out.println(otherintegerhash2);
  
  BigInteger x =  thisintegerhash.xor(otherintegerhash);
  BigInteger x2 =  thisintegerhash2.xor(otherintegerhash2);
  System.out.println(x.toString(2));
  System.out.println(x2.toString(2));
 }
}

输出结果:

11001111101111100101011111010000110110101110101110001100100

11001111101101100101011111010000110110101110101111001001100

467796836436368484

467726467692191308

111001000000101110101010000101001101010011010100110111100001001111100111111011101010010000001001111101101101110000000000000001011011111110101100100111001000

10000000000000000000000000000000000001000101000

从结果可以看出:

两个BigInteger表示的64位二进制数做异或操作,需要使用下面这个方法:

BigInteger(String val, int radix)  将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger。

例如:new BigInteger(otherstrhash, 2);

将字符串类型的64位二进制数转化为BigInteger类型的10进制表示形式,然后再对它们俩做异或操作。

这样得到的结果才是我们两个二进制数做异或操作后我们想要的正确结果:10000000000000000000000000000000000001000101000

如果我们不通过new BigInteger(otherstrhash, 2);转化,直接将String类型转换得到的BigInteger类型二进制数new BigInteger(otherstrhash);做异或操作,我们得到的结果会大大出乎意料,如下:

111001000000101110101010000101001101010011010100110111100001001111100111111011101010010000001001111101101101110000000000000001011011111110101100100111001000

2、将一个不规则的二进制数,如46位的二进制数转化为标准形式64位的二进制数,可以采用下面的方法:

  String c=new BigInteger(thisstrhash,2).xor(new BigInteger (otherstrhash,2)).toString(2);
  
  System.out.println(c);
  String d="0000000000000000000000000000000000000000000000000000000000000000"; //64个0
 
  c=d.substring(0,64-c.length())+c; 
  
  System.out.println(c);

输出结果为:

0000000000000000010000000000000000000000000000000000001000101000

转载于:https://my.oschina.net/HIJAY/blog/296817

你可能感兴趣的:(BigInteger类型的两个二进制数做异或操作后,希望得到的返回结果也为二进制数形式...)