samedi 18 avril 2020

Von Neumann Random Bytes Debiasing in Python

I need to create a method to debias biased bytes from the method get_raw_bytes(length) using von Neumann debiasing method. Here's my current attempt:

def get_debiased_bytes(length):
    arr_debiased_bytes = []
    debiased_byte = 0
    bit_counter = 0
    while len(arr_debiased_bytes) < length:
        raw_bytes = get_raw_bytes(length * 5)
        for byte in raw_bytes:
            for k in range(0, 8, 2):
                bit1 = byte >> k & 1
                bit2 = byte >> k + 1 & 1
                if bit1 != bit2:
                    debiased_byte = debiased_byte << 1 | bit1
                    bit_counter += 1
                    if bit_counter == 8:
                        arr_debiased_bytes.append(debiased_byte)
                        debiased_byte = 0
                        bit_counter = 0
    return bytes(arr_debiased_bytes[:length])

I think my code still can be improved and tidied up. Can anyone help me with this?




Aucun commentaire:

Enregistrer un commentaire