OK, here's a simple test function that runs through every possible 16 bit number, converts to various forms and checks for errors. Not sure this will help, but maybe it will clarify a few things. You can choose to convert to binary string representation as part of the conversion chain, or not. Just provide "True" as the argument if you want to test with binary conversion.KJM wrote: ↑Thu Jul 07, 2022 9:13 amSomething is troubling me Rob. It should take 2 bytes to represent 16 bits. But if I convert my 16 bit string of 1s & 0s to a character with d=int(bis, 2); bys=hex(d); r=chr(int(bys)) & send that over raw lora (without encryption) the receiver says it's received 1 byte. How is it possible to cram 65526 combinations into a single byte? I mean there could be 65536 unique characters but I can't understand how they can all be sent as variations of a single byte? To my mind a single byte can only handle 8 bits not 16?
The objective wasn't to showcase the most optimal form for the various conversions, but rather to show a series of potentially relevant conversions from integer through other forms of representation and back to integer and do so without errors.
Code: Select all
# Generate every possible 16 bit number
# Convert it to two 8 bit numbers
# Convert it to bytes data type
# Convert back to a 16 bit number and flag if they do not match
#
def int16_to_bytes_test(convert_to_binary_first=False):
for n in range(0,2**16):
n = n & 0xFFFF # Unnecessary. Just being paranoid to ensure we only have 16 bits
if convert_to_binary_first:
# To a 16 bit binary string representation
n_in_binary = f"{n:016b}"
# Convert into a tuple of two 8 bit numbers
# Doing it the hard way
broken_into_two_8_bit_numbers = int(n_in_binary[:8], 2), int(n_in_binary[8:], 2)
else:
# 16 bit to a tuple with two integers limited to a 0 to 256 range (8 bits)
broken_into_two_8_bit_numbers = int(n / 256), n % 256
# Convert to bytes
bytes_from_tuple = bytes(broken_into_two_8_bit_numbers)
# Convert back to 16 bit integer and compare
from_bytes_to_16_bit = bytes_from_tuple[0] * 256 + bytes_from_tuple[1]
# DEBUG ***** uncomment to see all data as generated
# print(f"n:{n:5d} two_8: {broken_into_two_8_bit_numbers} bytes: {str(bytes_from_tuple):>12} to_16:{from_bytes_to_16_bit:5d}")
# Compare and flag if they DO NOT match
if from_bytes_to_16_bit != n:
print(f"Error: {n} does not match the converted {from_bytes_to_16_bit}")
return
print("Every number passed the test")
int16_to_bytes_test(True)