Domanda

I'm a javascript code monkey, so this is virgin territory for me.

I have two "strings" that are just zeros and ones:

var first =  "00110101011101010010101110100101010101010101010";
var second = "11001010100010101101010001011010101010101010101";

I want to perform a bitwise & (which I've never before worked with) to determine if there's any index where 1 appears in both strings.

These could potentially be VERY long strings (in the thousands of characters). I thought about adding them together as numbers, then converting to strings and checking for a 2, but javascript can't hold precision in large intervals and I get back numbers as strings like "1.1111111118215729e+95", which doesn't really do me much good.

Can I take two strings of unspecified length (they may not be the same length either) and somehow use a bitwise & to compare them?

I've already built the loop-through-each-character solution, but 1001^0110 would strike me as a major performance upgrade. Please do not give the javascript looping solution as an answer, this question is about using bitwise operators.

È stato utile?

Soluzione

As you already noticed yourself, javascript has limited capabilities if it's about integer values. You'll have to chop your strings into "edible" portions and work your way through them. Since the parseInt() function accepts a base, you could convert 64 characters to an 8 byte int (or 32 to a 4 byte int) and use an and-operator to test for set bits (if (a & b != 0))

Altri suggerimenti

var first = "00110101011101010010101110100101010101010101010010001001010001010100011111",
    second = "10110101011101010010101110100101010101010101010010001001010001010100011100",
    firstInt = parseInt(first, 2),
    secondInt = parseInt(second, 2),
    xorResult = firstInt ^ secondInt, //524288
    xorString = xorResult.toString(2); //"10000000000000000000"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top