OK I wrote a solution last night but it feels a bit clunky. Here it is;
For the decimal integer range 0-255 this always produces a 2 digit hex byte where previously I was getting a single digit hex byte for decimal values below 10.
This is the functional outcome I was looking for but it does feel a bit cumbersome. I know that, in other coding environments, there are simpler ways of achieving this but I haven't yet found the magic solution in Micropython. Is there one?
Code:
def stable_bytes(decimal): hex_str = hex(decimal)# convert the decimal integer into a hex string if len(hex_str) <=3: #if the number of characters is 3 or fewer we will provide a padding zero to maintain a constant string length hex_str = hex_str[2:] #remove the first two characters to leave behind the single hex digit hex_str = '0x0' + hex_str # Add padding to the string to create a string with a 0x denoting a hex string and a leading zero and combine the remaining digit from above to create a 4 character string Clean_hex_str = ubinascii.hexlify(hex_str).decode() # Create a clean hex string bytes_result = ubinascii.unhexlify(Clean_hex_str) # Create a bytes object return bytes_resultThis is the functional outcome I was looking for but it does feel a bit cumbersome. I know that, in other coding environments, there are simpler ways of achieving this but I haven't yet found the magic solution in Micropython. Is there one?
Statistics: Posted by PhilPryer — Tue Apr 30, 2024 8:33 am