# How to use the classical expressions for qiskit for real backends?

I would like to build a quantum circuit that executes a gate based on mid-circuit measurements. In particular I want to create a $$n$$ qubit GHZ state using the scheme formulated to this question:https://quantumcomputing.stackexchange.com/a/26678/26583

How can I use qiskit classical expressions: https://docs.quantum.ibm.com/api/qiskit/circuit_classical to compute a sum mod 2 of $$a + b + c,$$ where $$a$$, $$b$$, and $$c$$ are mid-circuit measurement results? I don't need to use qiskit but anything that can access IBM backends.

Thank you!

Assume that your classical register is cr, then using Qiskit you can XOR the first three bits then apply an $$X$$-gate based on the expression value as follows:

from qiskit.circuit.classical import expr

_condition = expr.bit_xor(expr.bit_xor(cr[0], cr[1]), cr[2])
with circ.if_test(_condition):
circ.x(qr[3])


Note that, you can get a full implementation for the mentioned circuit from this blog post.

Edit: here is a full example tested with both Qiskit 0.46 and Qiskit 1.0:

from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.classical import expr
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit import transpile

qr = QuantumRegister(4, 'q')
cr = ClassicalRegister(3, 'c')
cr2 = ClassicalRegister(1, 'c2')
circ = QuantumCircuit(qr, cr, cr2)

circ.h(qr[0])
circ.h(qr[1])
circ.h(qr[2])
circ.measure(qr[0:3], cr)

_condition = expr.bit_xor(expr.bit_xor(cr[0], cr[1]), cr[2])
with circ.if_test(_condition):
circ.x(qr[3])

circ.measure(qr[3], cr2)

# Execute the circuit:
backend = GenericBackendV2(num_qubits=len(circ.qubits), control_flow=True)
tr_circ = transpile(circ, backend)
result = backend.run(tr_circ).result()
print(result.get_counts())

• When I try to use such a block in my circuit I get a TypeError: cannot unpack non-iterable Binary object. I am using the following code to simulate the circuit: python backend = GenericBackendV2(num_qubits=len(qc.qubits), control_flow=True) qc_trans = transpile(qc, backend) result = backend.run(qc_trans).result()
– ty.
Commented Apr 22 at 20:31
• I added a full example to my answer. Try it on your machine. Or, add your circuit-building code to the question so that I can examine it. Commented Apr 23 at 5:38
• I didn't have Aer installed. pip install qiskit-aer solved it. Thank you for the help!
– ty.
Commented Apr 23 at 6:33