Tag Archives: Boolean Logic

Performing a bitwise NOT on arbitrarily long integers

Here’s the surprisingly simple solution to a fairly challenging problem. I do not understand why PHPs GMP extension does not include a gmp_not() function.

function gmp_not($n) {
	
	# convert to binary string
	$n = gmp_strval($n, 2);
	
	# invert each bit, one at a time
	for($i = 0; $i < strlen($n); $i++) {
		$n[$i] = ~$n[$i];
	}
	
	# convert back to decimal
	return gmp_strval(gmp_init($n, 2), 10);
}

Logical XOR in Javascript

XOR (exclusive OR) is a boolean operation, like && and ||, but with the following logic: It is true if the expression on either side is true (like ||), but not if both sides are true (like &&).

Sometimes, in your JavaScript, you might want to do the following:

if( foo XOR bar ) { ... }

Unfortunately, JavaScript does not have a logical XOR operator. This article covers several methods of performing an XOR manually, and concludes with a surprisingly succinct way of doing it, summarized below.

The cleanest and best

The XOR operation can be described as “return true if the two boolean operands do not have the same value”. So the actual response that is wanted is just this:

if( foo != bar ) { ... }

That works if the two operands are both boolean true/false. However, to allow for other variable types (strings, expressions, etc.), it cannot work, since ‘string’ does not equal /regex/, even though the XOR operation would be expected to return false. So the operands need to be converted into boolean values first. This can be done like this:

foo ? true : false

However, it is easier and quicker to simply use the ! operator. This will give the opposite value – false instead of true, but as long as both operands get the same treatment, this will not affect the end result. So the simplest, cleanest version of the XOR operator, that works with any data types, including expressions, is this:

if( !foo != !bar ) { ... }