XOR logical operator

jerry80409
2 min readMay 28, 2020

--

XOR truth table

+-------+-------+---------+
| A | B | A XOR B |
+-------+-------+---------+
| false | false | false |
| false | true | true |
| true | false | true |
| true | true | false |
+-------+-------+---------+

XOR Karnaught Map (K-map)

Karnaught Map (K-map) is used to minimize boolean expressions, it’s very useful on the complex logic operator.

Reference from http://www.32x8.com, fill the XOR truth table and you can get SOP(Sum of product), POS(product of sum), Quine-McCluskey(SOP) result.

http://www.32x8.com/var2.html

SOP (Sum of product)

SOP means that pick the TRUE result and sum of them.

Sum of product

POS (Product of Sum)

POS means that pick the FALSE result and sum of them and use De Morgan’s laws to transfer it to return TRUE;

Product of Sum

Transform JAVA code

SOP

if ((!A && B) || (A && !B)) {  return true;
}

POS

if ((A || B) && (!A || !B)) {  return true;
}

Testing

Demo

@AllArgsConstructor
static class Foo {
boolean a;
boolean b;
}

static Map<Boolean, Foo> TRUTH_TABLE = new LinkedHashMap<>(4);
static {
TRUTH_TABLE.put(false, new Foo(false, false));
TRUTH_TABLE.put(true, new Foo(false, true));
TRUTH_TABLE.put(true, new Foo(true, false));
TRUTH_TABLE.put(false, new Foo(true, true));
}

private Boolean sop(Foo foo) {
if ((!foo.a && foo.b) || (foo.a && !foo.b)) {
return true;
}
return false;
}

private Boolean pos(Foo foo) {
if ((foo.a || foo.b) && (!foo.a) || !foo.b) {
return true;
}
return false;
}

private Boolean xorOp(Foo foo) {
return foo.a ^ foo.b;
}

Testing

@Test
void test_xor_sop() {
TRUTH_TABLE.forEach((expect, value) -> {
Boolean act = sop(value);
assertThat(act).isEqualTo(expect);
});
}

@Test
void test_xor_pos() {
TRUTH_TABLE.forEach((expect, value) -> {
Boolean act = pos(value);
assertThat(act).isEqualTo(expect);
});
}

@Test
void test_xor_op() {
TRUTH_TABLE.forEach((expect, value) -> {
Boolean act = xorOp(value);
assertThat(act).isEqualTo(expect);
});
}

--

--

jerry80409
jerry80409

Written by jerry80409

隨便記錄一些沒有整理很清楚的想法

No responses yet