简体   繁体   English

字符串Java之间的按位运算符

[英]Bitwise operators between String Java

I want to use bitwise operators between strings(stirngs has not the same length) in Java. 我想在Java中的字符串之间使用按位运算符(stirngs的长度不同)。

Actually, in case that I have two Strings 实际上,如果我有两个字符串

eg s1=test s2=sampleJAVA 例如s1 = test s2 = sampleJAVA

I convert strngs to binary: 我将strngs转换为二进制:

s1Binary=01110100 01100101 01110011 01110100 s1Binary = 01110100 01100101 01110011 01110100

s2Binary=01110011 01100001 01101101 01110000 01101100 01100101 01001010 01000001 01010110 01000001 s2Binary = 01110011 01100001 01101101 01110000 01101100 01100101 01001010 01000001 01010110 01000001

And I want to calculate two bitwise operators 我想计算两个按位运算符

  1. s1Binary | s1Binary | s2Binary s2Binary
  2. s1Binary & s2Binary s1Binary和s2Binary

I tried for two strings: 我尝试了两个字符串:

 String s1 = "test";
 byte[] a = s1.getBytes();
 String s1Binary = "";
 for (int i = 0; i < a.length; i++) {
      s1Binary = s1Binary + String.format("%8s", Integer.toBinaryString(a[i] & 0xFF)).replace(' ', '0');
  }
 /////// s2 /////
 String s2 = "sampleJAVA";
 byte[] b = s2.getBytes();
 String s2Binary = "";
 for (int i = 0; i < b.length; i++) {
      s2Binary = s2Binary + String.format("%8s", Integer.toBinaryString(b[i] & 0xFF)).replace(' ', '0');
  }

But I stuck there because I have two strings with different (binary) length 但是我被困在那里,因为我有两个长度不同(二进制)的字符串

You can pad the shorter string with leading zeros. 您可以用前导零填充较短的字符串。

turn 01110100 01100101 01110011 01110100 01110100 01100101 01110011 01110100

into 00000000 00000000 00000000 00000000 00000000 00000000 01110100 01100101 01110011 01110100 00000000 00000000 00000000 00000000 00000000 00000000 01110100 01100101 01110011 01110100

You can use BigInteger like this. 您可以像这样使用BigInteger。

String s1Binary = "01110100011001010111001101110100";
String s2Binary = "01110011011000010110110101110000011011000110010101001010010000010101011001000001";
BigInteger b1 = new BigInteger(s1Binary, 2);
BigInteger b2 = new BigInteger(s2Binary, 2);
System.out.println(b1.and(b2).toString(2));
System.out.println(b1.or(b2).toString(2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM