%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from random import randint
import hashlib
#These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def tobits(s):
    result = []
    for c in s:
        bits = bin(ord(c))[2:]
        bits = '00000000'[len(bits):] + bits
        result.extend([int(b) for b in bits])
    return ''.join([str(x) for x in result])

def frombits(bits):
    chars = []
    for b in range(int(len(bits) / 8)):
        byte = bits[b*8:(b+1)*8]
        chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
    return ''.join(chars)

#Alice cell, Bob can't see what's going in on here
m0 = tobits("Yes I want to go to the cinema with you!!!") 
m1 = tobits("No I dont want to go to the cinema with you...")
messageToSend = m1
Alice_bases = [randint(0,1) for x in range(len(messageToSend))]
qubits = list()
for i in range(len(Alice_bases)):
    mycircuit = QuantumCircuit(1,1)
    if(Alice_bases[i] == 0):
        if(messageToSend[i] == "1"):
            mycircuit.x(0)
    else:
        if(messageToSend[i] == "0"):
            mycircuit.h(0)
        else:
            mycircuit.x(0)
            mycircuit.h(0)
    qubits.append(mycircuit)

#Bob cell, Alice can't see what's going in on here
backend = Aer.get_backend('qasm_simulator')
measurements = list()
for i in range(len(Alice_bases)):
    qubit = qubits[i]
    if(Alice_bases[i] == 0):
        qubit.measure(0,0)
    else:
        qubit.h(0)
        qubit.measure(0,0)
    result = execute(qubit, backend, shots=1, memory=True).result()
    measurements.append(int(result.get_memory()[0]))
print("Alice message was: " + frombits(measurements))