Skip to main content
  • Pricing
Tutorials

Binary XOR: Compare Two Bit Strings

By Oakgen TeamPublished 1 min read

Share
Binary XOR: Compare Two Bit Strings

Binary XOR returns 1 where two corresponding bits differ and 0 where they match. It compares columns independently. There is no carry from one column to the next.

Compute a four-bit result

Compare 1101 and 1011. Start from the left. The first pair matches, the next two differ, and the last matches. The result is 0110, or 6 in decimal. The leading zero preserves the displayed four-bit width.

For unequal-width nonnegative values, right-align the operands and add leading zeros to the shorter input. Comparing 1 with 1010 at width four is the same as comparing 0001 with 1010. The result is 1011.

Pick a representation before using code

JavaScript's XOR operator coerces Number operands to signed 32-bit integers. That can drop high bits from a wide value. BigInt lets you work with larger integers, but both operands need to be BigInt. When presenting a bit mask, record the width and choose what to do if the input does not fit.

A useful check is to XOR the result with the second operand again. The bits toggled by the second operand will toggle back, recovering the first value at the same width.

Continue with Oakgen Agent

Coming soon: A dedicated browser XOR calculator.

Open in Oakgen Agent

Review the prefilled prompt before sending.

Open in Oakgen Agent

Sources

  1. MDN, JavaScript Bitwise XOR
Share