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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值