    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: All About XOR</title>
        <link>https://members.accu.org/index.php/journals/1915</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #109 - June 2012 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c310/">o109</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c310-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c310+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;All About XOR</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 03 June 2012 18:32:50 +01:00 or Sun, 03 June 2012 18:32:50 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Boolean operators are the bedrock of computer logic. Michael Lewin investigates a common one and shows thereâ€™s more to it than meets the eye.</p>
<p><strong>Body:</strong>&nbsp;<p>You probably already know what XOR is, but letâ€™s take a moment to formalise it. XOR is one of the sixteen possible binary operations on Boolean operands. That means that it takes 2 inputs (itâ€™s binary) and produces one output (itâ€™s an operation), and the inputs and outputs may only take the values of TRUE or FALSE (itâ€™s Boolean) â€“ see Figure 1. We can (and will) interchangeably consider these values as being 1 or 0 respectively, and that is why XOR is typically represented by the symbol &#8853;: it is equivalent to the addition operation on the integers modulo 2 (i.e. we wrap around so that 1 + 1 = 0)<a href="#FN01"><sup>1</sup></a> [<a href="#[SurreyUni]">SurreyUni</a>]. I will use this symbol throughout, except in code examples where I will use the C operator <code>^</code> to represent XOR.</p>

<table class="sidebartable">
	<tr>
		<td>
			<table class="journaltable">
				<tr>
					<th colspan="3">XOR Truth Table</th>
				</tr>
				<tr>
					<th>Input A</th>
					<th>Input B</th>
					<th>Output</th>
				</tr>
				<tr>
					<td>0</td>
					<td>0</td>
					<td>0</td>
				</tr>
				<tr>
					<td>0</td>
					<td>1</td>
					<td>1</td>
				</tr>
				<tr>
					<td>1</td>
					<td>0</td>
					<td>1</td>
				</tr>
				<tr>
					<td>1</td>
					<td>1</td>
					<td>0</td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td class="title">Figure 1</td>
	</tr>
</table>
 
<p>Certain Boolean operations are analogous to set operations (see Figure 2): AND is analogous to intersection, OR is analogous to union, and XOR is analogous to set difference. This is not just a nice coincidence; mathematically it is known as an isomorphism<a href="#FN02"><sup>2</sup></a> and it provides us with a very neat way to visualise and reason about such operations.</p>

<table class="sidebartable">
	<tr>
		<td><img style="width:33%;" src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-2a.png" /></td>
	</tr>
	<tr>
		<td><img style="width:33%;" src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-2b.png" /></td>
	</tr>
	<tr>
		<td><img style="width:33%;" src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-2c.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 2</td>
	</tr>
</table>


<h2>Important properties of XOR</h2>

<p>There are 4 very important properties of XOR that we will be making use of. These are formal mathematical terms but actually the concepts are very simple.</p>

<ol>
	<li><em>Commutative</em>: A &#8853; B = B &#8853; A
		<p>This is clear from the definition of XOR: it doesnâ€™t matter which way round you order the two inputs.</p>
	</li>
	<li><em>Associative</em>: A &#8853; ( B &#8853; C ) = ( A &#8853; B ) &#8853; C
		<p>This means that XOR operations can be chained together and the order doesnâ€™t matter. If you arenâ€™t convinced of the truth of this statement, try drawing the truth tables.</p>	
	</li>
	<li><em>Identity element</em>: A &#8853; 0 = A
		<p>This means that any value XORâ€™d with zero is left unchanged.</p>
	</li>
	<li><em>Self-inverse</em>: A &#8853; A = 0
		<p>This means that any value XORâ€™d with itself gives zero.</p>
	</li>
</ol>

<p>These properties hold not only when XOR is applied to a single bit, but also when it is applied bitwise to a vector of bits (e.g. a byte). For the rest of this article I will refer to such vectors as bytes, because it is a concept that all programmers are comfortable with, but donâ€™t let that make you think that the properties only apply to a vector of size 8.</p>

<h2>Interpretations</h2>

<p>We can interpret the action of XOR in a number of different ways, and this helps to shed light on its properties. The most obvious way to interpret it is as its name suggests, â€˜exclusive ORâ€™: A &#8853; B is true if and only if precisely one of A and B is true. Another way to think of it is as identifying <em>difference</em> in a pair of bytes: A &#8853; B = â€˜the bits where they differâ€™. This interpretation makes it obvious that A &#8853; A = 0 (byte A does not differ from itself in any bit) and A &#8853; 0 = A (byte A differs from 0 precisely in the bit positions that equal 1) and is also useful when thinking about toggling and encryption later on.</p>

<p>The last, and most powerful, interpretation of XOR is in terms of <em>parity</em>, i.e. whether something is odd or even. For any <em>n</em> bits, A1 &#8853; A2 &#8853; â€¦ &#8853; A<em><sub>n</sub></em> = 1 if and only if the number of 1s is odd. This can be proved quite easily by induction and use of associativity.  It is the crucial observation that leads to many of the properties that follow, including error detection, data protection and adding.</p>

<h2>Toggling</h2>

<p>Armed with these ideas, we are ready to explore some applications of XOR.  Consider the following simple code snippet:</p>

<pre class="programlisting">
  for (int n=x; true; n ^= (x ^ y)) 
    printf(&quot;%d &quot;, n);</pre>

<p>This will toggle between two values <code>x</code> and <code>y</code>, alternately printing one and then the other. How does it work? Essentially the combined value <code>x ^ y</code> â€˜remembersâ€™ both states, and one state is the key to getting at the other. To prove that this is the case we will use all of the properties covered earlier:</p>

<table>
	<tr>
		<td>&#160;&#160;B &#8853; ( A &#8853; B )</td>
		<td>(commutative )</td>
	</tr>
	<tr>
		<td>= B &#8853; ( B &#8853; A )</td>
		<td>(associative)</td>
	</tr>
	<tr>
		<td>= (B &#8853; B) &#8853; A</td>
		<td>(self-inverse)</td>
	</tr>
	<tr>
		<td>= 0 &#8853; A</td>
		<td>(identity element)</td>
	</tr>
	<tr>
		<td>= A </td>
		<td></td>
	</tr>
</table>

<p>Toggling in this way is very similar to the concept of a <em>flip-flop</em> in electronics: a â€˜circuit that has two stable states and can be used to store state informationâ€™ [<a href="#[Wikipedia-a]">Wikipedia-1</a>].</p>

<h2>Save yourself a register</h2>

<p>Toggling is all very well, but itâ€™s probably not that useful in practice. Hereâ€™s a function that is more useful. If you havenâ€™t encountered it before, see if you can guess what it does.</p>

<pre class="programlisting">
  void s(int&amp; a, int&amp; b)
  {
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
  }</pre>

<p>Did you work it out? Itâ€™s certainly not obvious, and the below equivalent function is even more esoteric:</p>

<pre class="programlisting">
  void s(int&amp; a, int&amp; b)
  {
    a ^= b ^= a ^= b;
  }</pre>
  
<p>Itâ€™s an old trick that inspires equal measures of admiration and vilification. In fact there is a whole repository of interview questions whose name is inspired by this wily puzzle: http://xorswap.com/. Thatâ€™s right, itâ€™s a function to swap two variables in place without having to use a temporary variable. Analysing the first version: the first line creates the XORâ€™d value. The second line comprises an expression that evaluates to <code>a</code> and stores it in <code>b</code>, just as the toggling example did. The third line comprises an expression that evaluates to <code>b</code> and stores it in <code>a</code>. And weâ€™re done! Except thereâ€™s a bug: what happens if we call <code>s(myVal, myVal)</code>? This is an example of <em>aliasing</em>, where two arguments to a function share the same location in memory, so altering one will affect the other. The outcome is that <code>myVal == 0</code> which is certainly not the semantics we expect from a swap function!</p>

<p>Perhaps there is some retribution for this much maligned idea, however. This is more than just a devious trick when we consider it in the context of assembly language. In fact XORâ€™ing a register with itself is the fastest way for the compiler to zero the register. </p>

<h2>Doubly linked list</h2>

<p>A node in a singly linked list contains a value and a pointer to the next node. A node in a doubly linked list contains the same, plus a pointer to the previous node. But in fact itâ€™s possible to do away with that extra storage requirement. Instead of storing either pointer directly, suppose we store the XORâ€™d value of the previous and next pointers [<a href="#[Wikipedia-b]">Wikipedia-2</a>] â€“ see Figure 3.</p>

<table class="sidebartable">
	<tr>
		<td><img style="width:80%" src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-3.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 3</td>
	</tr>
</table>

<p>Note that the nodes at either end store the address of their neighbours. This is consistent because conceptually we have XORâ€™ed that address with 0. Then the code to traverse the list looks like Listing 1, which was adapted from Stackoverflow [<a href="#[Stackoverflow]">Stackoverflow</a>].</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// traverse the list given either the head or
// the tail
void traverse( Node *endPoint )
{
  Node* prev = endPoint;
  Node* cur = endPoint;

  while ( cur )
  // loop until we reach a null pointer
  {
    printf( &quot;value = %d\n&quot;, cur-&gt;value);
    if ( cur == prev )
    
// only true on first iteration
      cur = cur-&gt;prevXorNext;
      // move to next node in the list
    else
    {
      Node* temp = cur;
      cur = (Node*)((uintptr_t)prev
         ^ (uintptr_t)cur-&gt;prevXorNext);
      // move to next node in the list
      prev = temp;
    }
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>This uses the same idea as before, that one state is the key to getting at the other. If we know the address of any consecutive pair of nodes, we can derive the address of their neighbours. In particular, by starting from one end we can traverse the list in its entirety. A nice feature of this function is that this same code can be used to traverse either forwards or backwards. One important caveat is that it cannot be used in conjunction with garbage collection, since by obfuscating the nodesâ€™ addresses in this way the nodes would get marked as unreachable and so could be garbage collected prematurely.</p>

<h2>Pseudorandom number generator</h2>

<p>XOR can also be used to generate pseudorandom numbers in hardware.  A pseudorandom number generator (whether in hardware or software e.g. <Code>
std::rand()</Code>
) is not truly random; rather it generates a deterministic sequence of numbers that appears random in the sense that there is no obvious pattern to it. This can be achieved very fast in hardware using a <em>linear feedback shift register</em>. To generate the next number in the sequence, XOR the highest 2 bits together and put the result into the lowest bit, shifting all the other bits up by one. This is a simple algorithm but more complex ones can be constructed using more XOR gates as a function of more than 2 of the lowest bits [<a href="#[Yikes]">Yikes</a>]. By choosing the architecture carefully, one can construct it so that it passes through all possible states before returning to the start of the cycle again (Figure 4).</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-4.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 4</td>
	</tr>
</table>

<h2>Encryption</h2>
<p>The essence of encryption is to apply some <em>key</em> to an input message in order to output a new message. The encryption is only useful if it is very hard to reverse the process. We can achieve this by applying our key over the message using XOR (see Listing 2).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
string EncryptDecrypt(string inputMsg,string key)
{
  string outputMsg(inputMsg);

  short unsigned int keyLength = key.length();
  short unsigned int strLength =
     inputMsg.length();

  for(int v=0, k=0;v&lt;strLength;++v)
  {
    outputMsg[v] = inputMsg[v]^key[k];
    ++k;
    k = k % keyLength;
  }
  return outputMsg;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>The choice of key here is crucial to the strength of the encryption. If it is short, then the code could easily be cracked using the centuries-old technique of frequency analysis. As an extreme example, if the key is just 1 byte then all we have is a <em>substitution cipher</em> that consistently maps each letter of the alphabet to another one. However, if the key is longer than the message, and generated using a â€˜<em>truly random</em>â€™ hardware random number generator, then the code is unbreakable [<a href="#[Wikipedia-c]">Wikipedia-3</a>]. In practice, this â€˜<em>truly random</em>â€™ key could be of fixed length, say 128 bits, and used to define a <em>linear feedback shift register</em> that creates a  pseudorandom sequence of arbitrary length known as a <em>keystream</em>. This is known as a <em>stream cipher</em>, and in a real-worl situation this would also be combined with a secure hash function such as <em>md5</em> or <em>SHA-1</em>. </p>

<p>Another type of cipher is the <em>block cipher</em> which operates on the message in blocks of fixed size with an unvarying transformation. An example of XOR in this type of encryption is the International Data Encryption Algorithm (IDEA) [<a href="#[Wikipedia-d]">Wikipedia-4</a>].</p>

<p>The best-known encryption method is the <em>RSA algorithm</em>. Even when the  above algorithm is made unbreakable, it has one crucial disadvantage: it is not a <em>public key</em> system like RSA. Using RSA, I can publish the key others need to send me encrypted messages, but keep secret my private key used to decrypt them. On the other hand, in XOR encryption the same key is used to encrypt and decrypt (again we see an example of toggling). Before you can send me encrypted messages I must find a way to secretly tell you the key to use. If an adversary intercepts that attempt, my code is compromised because they will be able to decrypt all the messages you send me. </p>

<h2>Error detection</h2>

<p>Now we will see the first application of XOR with respect to <em>parity</em>. There are many ways to defend against data corruption when sending digital information. One of the simplest is to use XOR to combine <em>all</em> the bits together into a single <em>parity bit</em> which gets appended to the end of the message. By comparing the received parity bit with the calculated one, we can reliably determine when a single bit has been corrupted (or indeed any odd number of bits). But if 2 bits have been corrupted (or indeed any even number of bits) this check will not help us.</p>

<p><em>Checksums</em> and <em>cyclic redundancy checks</em> (CRC) extend the concept to longer check values and reducing the likelihood of collisions and are widely used. Itâ€™s important to note that such checks are <em>error-detecting</em> but not <em>error-correcting</em>: we can tell that an error has occurred, but we donâ€™t know where it occurred and so canâ€™t recover the original message. Examples of error-correcting codes that also rely on XOR are <em>BCH</em> and <em>Reed-Solomon</em> [<a href="#[Wikipedia-e]">Wikipedia-5</a>][<a href="#[IEEEXplore]">IEEEXplore</a>].</p>

<h2>RAID data protection</h2>

<p>The next application of XORâ€™s parity property is RAID (Redundant Arrays of Inexpensive Disks) [<a href="#[Mainz]">Mainz</a>] [<a href="#[DataClinic]">DataClinic</a>]. It was invented in the 1980s as a way to recover from hard drive corruption. If we have <em>n</em> hard drives, we can create an additional one which contains the XOR value of all the others:</p>

<p>A* = A<sub>1</sub> &#8853; A<sub>2</sub> &#8853; â€¦ &#8853; A<em><sub>n</sub></em></p>

<p>This introduces <em>redundancy</em>: if a failure occurs on one drive, say A1, we can restore it from the others since:</p>

<table>
	<tr>
		<td>&#160;&#160;A<sub>2</sub> &#8853; â€¦ &#8853; A<em><sub>n</sub></em> &#8853; A*</td>
		<td></td>
	</tr>
	<tr>
		<td>= A<sub>2</sub> &#8853; â€¦ &#8853; A<em><sub>n</sub></em> &#8853; (A<sub>1</sub> &#8853; A<sub>2</sub> &#8853; â€¦ &#8853; A<em><sub>n</sub></em>)</td>
		<td>(definition of A*)</td>
	</tr>
	<tr>
		<td>= A<sub>1</sub> &#8853; (A<sub>2</sub> &#8853; A<sub>2</sub>) &#8853;â€¦ &#8853; (A<em><sub>n</sub></em> &#8853; A<em><sub>n</sub></em>)</td>
		<td>(commutative and associative:	rearrange terms)</td>
	</tr>
	<tr>
		<td>= A<sub>1</sub> &#8853; 0 &#8853;â€¦ &#8853; 0</td>
		<td>(self-inverse)</td>
	</tr>
	<tr>
		<td>= A<sub>1</sub></td>
		<td>(identity element)</td>
	</tr>
</table>

<p>This is the same reasoning used to explain toggling earlier, but applied to <em>n</em> inputs rather than just 2.</p>

<p>In the (highly unlikely) event that 2 drives fail simultaneously, the above would not be applicable so there would be no way to recover the data.</p>

<h2>Building blocks of XOR</h2>

<p>Letâ€™s take a moment to consider the fundamentals of digital computing, and we will see that XOR holds a special place amongst the binary logical operations.</p>

<p>Computers are built from logic gates, which are in turn built from transistors. A transistor is simply a switch that can be turned on or off using an electrical signal (as opposed to a mechanical switch that requires a human being to operate it). So for example, the AND gate can be built from two transistors in series, since <em>both</em> switches must be closed to allow current to flow, whereas the OR gate can be built from two transistors in parallel, since closing <em>either</em> switch will allow the current to flow.</p>

<p>Most binary logical operations can be constructed from two or fewer transistors; of all 16 possible operations, the only exception is XOR (and its complement, XNOR, which shares its properties). Until recently, the simplest known way to construct XOR required six transistors [<a href="#[Hindawi]">Hindawi</a>]: the simplest way to see this is in the diagram below, which comprises three gates, each of which requires two transistors. In 2000, Bui <em>et al</em> came up with a design using only four transistors [<a href="#[Bui00]">Bui00</a>] â€“ see Figure 5.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-5.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 5</td>
	</tr>
</table>

<h2>Linear separability</h2>

<p>Another way in which XOR stands apart from other such operations is to do with <em>linear separability</em>. This is a concept from Artificial Intelligence relating to classification tasks. Suppose we have a set of data that fall into two categories. Our task is to define a single boundary line (or, extending the notion to higher dimensions, a hyperplane) that neatly partitions the data into its two categories. This is very useful because it gives us the predictive power required to correctly classify new unseen examples. For example, we might want to identify whether or not someone will default on their mortgage payments using only two clues: their annual income and the size of their property. Figure 6 is a hypothetical example of how this might look.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-6.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 6</td>
	</tr>
</table>

<p>A new mortgage application might be evaluated using this model to determine whether the applicant is likely to default.</p>

<p>Not all problems are neatly separable in this way. That means we either need more than one boundary line, or we need to apply some kind of non-linear transformation into a new space in which it is linearly separable: this is how machine learning techniques such as neural networks and support vector machines work. The transformation process might be computationally expensive or completely unachievable. For example, the most commonly used and rigorously understood type of neural network is the <em>multi-layer perceptron</em>. With a single layer it is only capable of classifying linearly separable problems. By adding a second layer it can transform the problem space into a new space in which the data is linearly separable, but thereâ€™s no guarantee on how long it may take to converge to a solution. </p>

<p>So where does XOR come into all this? Letâ€™s picture our binary Boolean operations as classification tasks, i.e. we want to classify our four possible inputs into the class that outputs TRUE and the class that outputs FALSE. Of all the 16 possible binary Boolean operations, XOR is the only one (with its complement, XNOR) that is not linearly separable with a single boundary line: two lines are required, as the diagram in Figure 7 demonstrates.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-7a.png" /></td>
	</tr>
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-7b.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 7</td>
	</tr>
</table>

<h2>Inside your ALU</h2>

<p>XOR also plays a key role inside your processorâ€™s <em>arithmetic logic unit</em> (ALU). Weâ€™ve already seen that it is analogous to addition modulo 2, and in fact that is exactly how your processor calculates addition too. Suppose first of all that you just want to add 2 bits together, so the output is a number between 0 and 2. Weâ€™ll need two bits to represent such a number. The lower bit can be calculated by XORâ€™ing the inputs. The upper bit (referred to as the â€˜carry bitâ€™) can be calculated with an AND gate because it only equals 1 when both inputs equal 1. So with just these two logic gates, we have a module that can add a pair of bits, giving a 2-bit output. This structure is called a <em>half adder</em> and is depicted in Figure 8.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-8.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 8</td>
	</tr>
</table>


<p>Now of course we want to do a lot more than just add two bits: just like you learnt in primary school, we need to carry the â€˜carry bitâ€™ along because it will play a part in the calculation of the higher order bits. For that we need to augment what we have into a <em>full adder</em>. Weâ€™ve added a third input that enables us to pass in a carry bit from some other adder. We begin with a half adder to add our two input bits. Then we need another half adder to add the result to the input carry bit. Finally we use an OR gate to combine the carry bits output by these two half adders into our overall output carry bit. (If youâ€™re not convinced of this last step, try drawing the truth table.) This structure is represented in Figure 9.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-9.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 9</td>
	</tr>
</table>


<p>Now we are able to chain as many of these adders together as we wish in order to add numbers of any size. The diagram below shows an 8-bit adder array, with the carry bits being passed along from one position to the next. Everything in electronics is modular, so if you want to add 32-bit numbers you could buy four of these components and connect them together (see Figure 10).</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol109/Lewin/Lewin-10.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 10</td>
	</tr>
</table>


<p>If you are interested in learning more about the conceptual building blocks of a modern computer, Charles Petzoldâ€™s book <em>Code</em> comes highly recommended.</p>

<h2>More detail on the Group Theory</h2>

<p>For those comfortable with the mathematics, here is a bit more detail of how XOR fits into group theory.</p>

<p>An <em>algebraic structure</em> is simply a mathematical object (S, ~) comprising a set S and a binary operation ~ defined on the set.</p>

<p>A group is an algebraic structure such that the following 4 properties hold:</p>

<ol>
	<li>~ is closed over X, i.e. the outcome of performing ~ is always an element of X</li>
	<li>~ is associative</li>
	<li>An identity element e exists that, when combined with any other element of X, leaves it unchanged</li>
	<li>Every element in X has some inverse that, when combined with it, gives the identity element</li>
</ol>

<p>We are interested in the operation XOR as applied to the set of Boolean vectors S = {T, F}<em><sup>N</sup></em>, i.e. the set of vectors of length <em>N</em> whose entries can only take the values T and F. (I mean <em>vector</em> in the mathematical sense, i.e. it has fixed length. Do not confuse this with the C++ data structure <code>std::vector</code>, which has variable length.)We have already seen that XOR is associative, that the vector (F, â€¦ F) is the identity element and that every element has itself as an inverse. Itâ€™s easy to see that it is also closed over the set. Hence (S, XOR) is a group. In fact it is an <em>Abelian</em> group because we showed above that XOR is also commutative.</p>

<p>Two groups are said to be <em>isomorphic</em> if there is a one-to-one mapping between the elements of the sets that preserves the operation. I wonâ€™t write that out formally (itâ€™s easy enough to look up) or prove the isomorphisms below (letâ€™s call that an exercise for the reader). Instead I will just define them and state that they are isomorphisms.</p>

<p>The group ({T, F}<em><sup>N</sup></em>, XOR) is isomorphic to the group ({0, 1}<em><sup>N</sup></em>, +) of addition modulo 2 over the set of vectors whose elements are integers mod 2. The isomorphism simply maps T to 1 and F to 0.</p>

<p>The group ({T, F}<em><sup>N</sup></em>, XOR) is also isomorphic to the group (P(S), Î”) of symmetric difference Î” over the power set of N elements<a href="#FN03"><sup>3</sup></a>: the isomorphism maps T to â€˜included in the setâ€™ and F to â€˜excluded from the setâ€™ for each of the N entries of the Boolean vector.</p>

<p>Letâ€™s take things one step further by considering a new algebraic structure called a <em>ring</em>. A ring (S,+, Ã—) comprises a set S and a pair of binary operations + and Ã— such that S is an Abelian group under + and a semigroup<a href="#FN04"><sup>4</sup></a> under Ã—. Also Ã— is distributive over +. The symbols + and Ã— are chosen deliberately because these properties mean that the two operations behave like addition and multiplication.</p>

<p>Weâ€™ve already seen that XOR is an Abelian group over the set of Boolean vectors, so it can perform the role of the + operation in a ring. It turns out that AND fulfils the role of the * operation. Furthermore we can extend the isomorphisms above by mapping AND to multiplication modulo 2 and set intersection respectively. Thus we have defined three isomorphic rings in the spaces of Boolean algebra, modulo arithmetic and set theory.</p>

<h2>References</h2>

<p class="bibliomixed">
<a id="[Bui00]"></a>
[Bui00]  H. T. Bui, A. K. Al-Sheraidah, and Y. Wang, â€˜New 4-transistor XOR and XNOR designsâ€™, in &lt;ArticleRefTitle&gt;
Proceedings of the 2nd IEEE Asia Pacific Conference&lt;/ArticleRefTitle&gt;
</p>

<p class="bibliomixed"><a id="[DataClinic]">[DataClinic]</a> <a href="http://www.dataclinic.co.uk/raid-parity-xor.htm">http://www.dataclinic.co.uk/raid-parity-xor.htm</a></p>

<p class="bibliomixed"><a id="[Hindawi]">[Hindawi]</a> <a href="http://www.hindawi.com/journals/vlsi/2009/803974/">http://www.hindawi.com/journals/vlsi/2009/803974/</a></p>

<p class="bibliomixed"><a id="[IEEEXplore]">[IEEEXplore]</a> <a href="http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=1347837">http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=1347837</a></p>

<p class="bibliomixed"><a id="[Mainz]">[Mainz]</a> <a href="http://www.staff.uni-mainz.de/neuffer/scsi/what_is_raid.html">http://www.staff.uni-mainz.de/neuffer/scsi/what_is_raid.html</a></p>

<p class="bibliomixed"><a id="[Stackoverflow]">[Stackoverflow]</a> <a href="http://stackoverflow.com/questions/3531972/c-code-for-xor-linked-list">http://stackoverflow.com/questions/3531972/c-code-for-xor-linked-list</a></p>

<p class="bibliomixed"><a id="[SurreyUni]">[SurreyUni]</a> <a href="http://www.ee.surrey.ac.uk/Projects/Labview/minimisation/karnaugh.html">http://www.ee.surrey.ac.uk/Projects/Labview/minimisation/karnaugh.html</a></p>

<p class="bibliomixed"><a id="[Wikipedia-a]">[Wikipedia-1]</a> <a href="http://en.wikipedia.org/wiki/Flip-flop_%28electronics%29">http://en.wikipedia.org/wiki/Flip-flop_%28electronics%29</a></p>

<p class="bibliomixed"><a id="[Wikipedia-b]">[Wikipedia-2]</a> <a href="http://en.wikipedia.org/wiki/XOR_linked_list">http://en.wikipedia.org/wiki/XOR_linked_list</a></p>

<p class="bibliomixed"><a id="[Wikipedia-c]">[Wikipedia-3]</a> <a href="http://en.wikipedia.org/wiki/XOR_cipher">http://en.wikipedia.org/wiki/XOR_cipher</a></p>

<p class="bibliomixed"><a id="[Wikipedia-d]">[Wikipedia-4]</a> <a href="http://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm">http://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm</a></p>

<p class="bibliomixed"><a id="[Wikipedia-e]">[Wikipedia-5]</a> <a href="http://en.wikipedia.org/wiki/Finite_field_arithmetic">http://en.wikipedia.org/wiki/Finite_field_arithmetic</a></p>

<p class="bibliomixed"><a id="[Yikes]">[Yikes]</a> <a href="http://www.yikes.com/~ptolemy/lfsr_web/index.htm">http://www.yikes.com/~ptolemy/lfsr_web/index.htm</a></p>

<p class="footnotes"></p>
<ol>
	<li><a id="FN01"></a>In this way, complex logical expressions can be reasoned about and simplified using modulo arithmetic. This is much easier than the commonly taught method of using Karnaugh maps, although OR operations do not map neatly in this way.</li>
	<li><a id="FN02"></a>Formally, the actions of XOR and AND on {0,1}<em><sup>N</sup></em> form a <em>ring</em> that is <em>isomorphic</em> to the actions of set difference and union on sets. For more details see the appendix.</li>
	<li><a id="FN03"></a>The <em>power set</em> means the set of all possible subsets, i.e. this is the set of all sets containing up to N elements.</li>
	<li><a id="FN04"></a>A <em>semigroup</em> is a group without the requirement that every element has an inverse.</li>
</ol>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
