1,105,332 Community Members

Lookup between binary string and binary value byte

Member Avatar
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
 
0
 

Lookup table is usually the fastest method to find function value, if number of values is small. Here we demonstrate the principle by using task of showing the value of byte as binary string or transforming binary string to byte binary value.

""" Preparing lookup tables for transforming byte value to binary string or
    8 bit binary string to byte value

"""
# list suffice for integer lookup
byte_to_bin = ["{0:08b}".format(byte) for byte in range(256)]
# to lookup zero padded string dict is needed
bin_to_byte = dict(reversed(value) for value in enumerate(byte_to_bin))

if __name__== '__main__':
    for testing in range(256):
        assert byte_to_bin[testing].lstrip('0') or '0' == bin(testing)[2:]
        assert bin_to_byte[byte_to_bin[testing].zfill(8)] == testing
    print('Verified')
Member Avatar
Tony Veijalainen

Specialties:
IT/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

You
Post:
Start New Discussion
View similar articles that have also been tagged: