[ Log On ]
  • Home
  • Tst
  • Cha
  • Enc
  • Code
  • IP
  • Fun
  • Sub
  • DigF
  • Cis
  • Com
  • Db
  • About
  • Netsim

Binary equations (using Python eval)

 

Back Python can use the eval() method to take a string and run it. In this case we calculate the Truth Table for a binary equation with a and b:

Bit operation

Enter a binary operation with a and b. You can use the bitwise operators (&,|,^ or ~) or binary names (or, and, xor):

Bit value 1:

Try an example

  • [a ^ b Calc] [a | b Calc]
  • [a & b Calc] [~(a & b) Calc]
  • [~(a | b) Calc] [a or b Calc]
  • [a xor b Calc] [(a and b) or b Calc]
  • [(a and b) or not(b) Calc] [not(a) and not(b) Calc]
  • [not(a) or not(b) Calc] [not(a) or b Calc]
  • [not(a) and b Calc] [a Calc]
  • [not(a) Calc] [a or not(a or b) Calc]
  • [a or b or c Calc] [a or not(b) or c Calc]
  • [a and not (b or c) Calc] [not (a) or not(b) or c Calc]
  • [a and not (b and c) Calc] [not (a) or b or c Calc]
  • [a or b and not(c) Calc] [a and b and not(c) Calc]
  • [(a and b) or (b and c) and d Calc]

Sample run

The following is a sample run:

Operator:       a ^ b
A       B       Z
-----------------
0       0       0
0       1       1
1       0       1
1       1       0

Code

The following is the Python code:

import sys

operator = "a ^ b"

if (len(sys.argv)>1):
        operator=sys.argv[1]

def nor(p, q):
    return ~ (p | q) & 0x01

def nand(p, q):
    return ~(p & q) & 0x01

def replace(op):
	op = op.replace("xor","^")
	op = op.replace("and","&")
	op = op.replace("or","|")
	op = op.replace("not","~")
	return(op)

operator = replace(operator)

if ('c' in operator.lower()):
	print "Operator:\t",operator
	print "A\tB\tC\tZ"
	print "-------------------------"
	for a in range(0,2):
		for b in range(0,2):
			for c in range(0,2):
				print a,"\t",b,"\t",c,"\t",(eval(operator) & 0x01)
else:
	print "Operator:\t",operator
	print "A\tB\tZ"
	print "-------------------------"
	for a in range(0,2):
		for b in range(0,2):
			print a,"\t",b,"\t",(eval(operator) & 0x01)

AND (Z=A.B)

A B Z
-----
0 0 0
0 1 0
1 0 0
1 1 1

OR (Z=A+B)

A B Z
-----
0 0 0
0 1 1
1 0 1
1 1 1

NAND (Z=A.B)

A B Z
-----
0 0 1
0 1 1
1 0 1
1 1 0

NOR (Z=A+B)

A B Z
-----
0 0 1
0 1 0
1 0 0
1 1 0

X-OR (Z=A⊕B)

A B Z
-----
0 0 0
0 1 1
1 0 1
1 1 0

The electronic gates used are: