Logic Gates in C++

What they are & how they’re used.

Jake Cutter
Technology Hits
2 min readJun 28, 2021

--

During a program, we can run checks on the values the computers read and ignore. This is like loops because it is a sort of conditional statement. What’s going to be covered are the four different gates, their output, and how they may be used in an example.

Photo by Aron Visuals on Unsplash

Gate One: AND (&)

AND takes two bits, which is 1/4 of a full byte, and helps the computer determine if it is a 1 or 0. This is because computers read off of binary, which is a bunch of 1’s and 0’s. In an AND statement, in order for it to be true, both bits have to be either 1 or 0. So two 1’s; otherwise, it will output a 0.

Gate Two: OR(|)

OR takes two bits and determines if either bit is 1. If there is one, then it will output a 1.

Gate Three: NOT(~)

NOT takes the opposite of a number. For example, if a number like 7 is 0000- 0111, then it will flip all of the bits over. (1111- 1000)

Gate Four: XOR(^)

XOR, or exclusive or, takes the two bits and looks for if both are the same number. If they are it will print out the opposite of those numbers. So two one’s will print out a 0, and two zeroes will print out a 1.

Examples:

n = (leftop << i) & 1;

a = (rightop << i) & 1;

carry = (a & n ) | (a & carry) | (n & carry);

result |= (a ^ n ^ carry);

Reasoning:

The two operands, n & a, are used in an addition operation. Carry is the number left over from the addition similar to by-hand addition. XOR is the result because it takes into account carry’s number along with how many 1’s in the numbers such as 2 + 3.

Example Two:

Add(~result, 1);

Reasoning:

In the above statement, the Add function is used in a two’s complement, which is how a computer sees a negative number. More on this in the future. The result from subtraction is NOTed and then added with one.

Citation:

Marz, Stephen. Professor. University of Tennessee. Knoxville, Tennessee. 2021

--

--