Java-位操作

标签 java

我有以下 Java 代码:

long a = Long.parseLong("11001100", 2);
long b = Long.parseLong("11000000", 2);
int npos = 0 ;
int pos = 0 ;
long n = ~(a ^ b) ;
int cnt = 0;
while (n != 0) {
  pos++ ;
  if ((n & 3) == 3) cnt++; // count how many matches
  else{
    npos = pos ;  // position that not matched also giving wrong which should be 2 nd position.
  }
  n >>>= 2;
}

System.out.println(npos + "  " + cnt) ; // also print which two bits are not matched i.e. 00 and 11

我试图找出两个整数中有多少个两位序列匹配。我还想找出哪两位不匹配。有人可以帮我怎么做吗?

PS:我的原始代码中没有字符串,只有整数。因此,我无法进行字符串操作。

编辑:

long a = Long.parseLong("11000100", 2);
long b = Long.parseLong("11000000", 2);
long mask = 0x03;
int npos = 0 ;
int cnt = 0;
long p1 = 0;
long p2 = 0;
for (int pos = 0; pos < 64; pos++, mask <<= 2) {

  if ((a & mask) == (b & mask)) {
     cnt++; // count how many matches
  } else {
    npos = pos ;  // *last* position that did not match
    p1 = (a & mask) ; // two bits that not matched
    p2 = (b & mask) ; // two bits that not matched
  }
}

  System.out.println(npos + "  " + cnt + " " + p1 + " " + p2) ; // also print which two bits are not matched i.e. 00 and 01

最佳答案

您将整数解析为以 10 为基数的数字,您可能希望将它们解析为二进制整数,为此,请使用具有基数参数的方法:

long a = Long.parseInt("11001100", 2);
long b = Long.parseInt("11000000", 2);

使用掩码运行循环比较 2 个值可能会更容易:

long mask = 0x03;
int npos = 0 ;
int cnt = 0;

for (int pos = 0; pos < 32; pos++, mask <<= 2) {

  if ((a & mask) == (b & mask)) {
     cnt++; // count how many matches
  } else {
    npos = pos ;  // *last* position that did not match
  }
}

关于Java-位操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11852164/

相关文章:

java - 带有列表作为单个键值的属性文件

java - MySQL Java语法错误

java - 什么决定了Tomcat Java进程的当前工作目录?

java - BoxLayout can't be shared error while setting it for JPanel 如何解决?

java - 为 CSV 文件创建标题

java - 使用返回整数列表的 power mock 测试私有(private)方法

java - 什么时候加载类?

java - contains 方法遇到问题

java - 无法让一个类的方法使用 Java 中另一类的用户输入

java - Stackdriver Logback 附加程序停止应用程序