【问题标题】:How to compare two binary values in javascript/node js?如何比较 javascript/node js 中的两个二进制值?
【发布时间】:2016-10-26 10:56:47
【问题描述】:

我有两个字符串

var a = "10001010";
var b = "10110010";

那么在两个字符串中找出相似之处的函数是什么, 在这种情况下,该函数将返回此值;

A 和 B 共有 5 位数字;如下;

var a = "10001010";

var b = "10110010";

我怎样才能得到这个值?

我需要这两个字符串之间的相似之处。

【问题讨论】:

  • 输出应该是什么格式?索引还是二进制数据?
  • 预期的结果是什么,到目前为止您已经尝试过什么?
  • @gurvinder372 输出应该是二进制数据。

标签: javascript string compare comparison


【解决方案1】:

您可以使用 bitwise XOR ^ 与字符串的数值和值 28 - 1。

在二进制结果中,单个1 表示ab0 的值相同。

   value    binary  dec  comment
--------  --------  ---  ---------------------------------------
       a  10001010  138
       b  10110010  178
--------  --------  ---
       ^  00111000   56  it shows only the changed values with 1
2^^8 - 1  11111111  255
--------  --------  ---
       ^  11000111  199  result with 1 for same value, 0 for not

var a = parseInt("10001010", 2),
    b = parseInt("10110010", 2),
    result = (a ^ b) ^ (1 << 8) - 1;

console.log(result);
console.log(result.toString(2));

【讨论】:

  • 这看起来很不错。这种异或运算的效率如何。想象一下,我在同一个案例中比较了数千个。
  • 它应该足够快,它只是一个二进制操作。
  • 谢谢!它正常工作,没有任何明显的开销。
【解决方案2】:

我想,你可以像这样比较它们

("10001010" > "10110010") --> false
("10001010" < "10110010") --> true
("10001010" < "00110010") --> false
("00110010" == "00110010") --> true

【讨论】:

    【解决方案3】:

    我已经写了一个逻辑来做到这一点enter link description here

    var test = "10001010";
    var test2  = "10110010";
    var testArray = test.split('');
    var testArray2 = test2.split('');
    var resultArray = [];
    for(index = 0; testArray.length > index;index++ ){
        if(testArray[index] === testArray2[index]){
         resultArray.push(testArray[index])
        }else{
          resultArray.push("*")
        }
    }
    
    console.log(resultArray.join(""));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-26
      • 2016-06-29
      • 2011-06-14
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      相关资源
      最近更新 更多