Simulating bitwise xor and negation

Dear students,

Emerald does not have bitwise xor and negation built-in. You might want these operators for implementing a hash function in Home Exam 1. Luckily, bitwise negation can be simulated using integer negation and subtraction, and xor can be simulated using bitwsise or, and, and negation.

Here is a sample program that

  1. implements both bitwise negation and xor,
  2. shows that the (bitwise) negation of 0 is (-1), and vice-versa (recall two's complement arithmetic), and
  3. prints out the truth-table for xor.
const xorneg <- object xorneg
  function neg[x : Integer] -> [y : Integer]
    y <- -x - 1
  end neg
  function xor[x : Integer, y : Integer] -> [z : Integer]
    z <- (x | y) & self.neg[(x & y)]
  end xor
  initially
    stdout.putstring["(neg)   0  ~> " || (self.neg[0]).asstring || "\n"]
    stdout.putstring["(neg) (-1) ~>  " || (self.neg[-1]).asstring || "\n"]
    stdout.putstring["\n"]
    stdout.putstring["0 (xor) 0 ~> " || (self.xor[0,0]).asstring || "\n"]
    stdout.putstring["0 (xor) 1 ~> " || (self.xor[0,1]).asstring || "\n"]
    stdout.putstring["1 (xor) 0 ~> " || (self.xor[1,0]).asstring || "\n"]
    stdout.putstring["1 (xor) 1 ~> " || (self.xor[1,1]).asstring || "\n"]
  end initially
end xorneg

--

Oleks

Published Mar. 18, 2019 2:51 PM - Last modified Mar. 18, 2019 2:53 PM