I need to create a method to debias biased bytes
from the method get_raw_bytes(length)
using von Neumann debiasing method.
Von Neumann method takes two bits at a time. If the input is 01 it will output 0, if the input is 10, it will output 1, if the input is 00 or 11, it won't output anything.
Example:
Raw : [11010110, 11001001, 01101000]
Debiased : [00110011]
Here's my current code:
def get_raw_bytes(length):
return open('/dev/hwrng', 'rb').read(length)
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?
get_raw_bytes
as well. \$\endgroup\$bytes
is actually a function, that as well. \$\endgroup\$get_raw_bytes
definition.bytes
is Python's built-in function to convert an array of 8-bit integers intobytes
data type. \$\endgroup\$