Search code examples
javascriptstringcomparecomparison

How to compare two binary values in javascript/node js?


I have two string

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

So What will be the function to find out Similarities in two string, in that case that function will return this value;

A and B have 5 Digits in common; which are as below;

var a = "10001010";

var b = "10110010";

How can I get this values?

I need similarities between this two strings.


Solution

  • You could use bitwise XOR ^ with the numerical values of the strings and value of 28 - 1.

    In the binary result, a single 1 means same value of a and b and 0 means not.

       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));