MLE/03_euler_gen_alg/utils.py

46 lines
1.7 KiB
Python

def clean_binary_string(binary_str, length=32):
"""Clean and format a binary string to ensure proper format"""
# Remove any whitespace and ensure proper length
cleaned = ''.join(binary_str.split())
return cleaned.zfill(length)
def grey_to_bin(gray):
"""Convert Gray code to binary, operating on the integer value directly"""
# Clean and format input string
gray = clean_binary_string(gray, 32)
try:
num = int(gray, 2) # Convert string to integer
mask = num
while mask != 0:
mask >>= 1
num ^= mask
return format(num, '032b') # Always return 32-bit string
except ValueError as e:
print(f"Error in grey_to_bin with input: '{gray}'")
raise e
def bin_to_grey(binary):
"""Convert binary to Gray code using XOR with right shift"""
# Clean and format input string
binary = clean_binary_string(binary, 32)
try:
num = int(binary, 2) # Convert string to integer
gray = num ^ (num >> 1) # Gray code formula: G = B ^ (B >> 1)
return format(gray, '032b') # Always return 32-bit string
except ValueError as e:
print(f"Error in bin_to_grey with input: '{binary}'")
raise e
def bin_to_param(binary, q_min = 0.0, q_max = 10.0):
"""Convert one binary string to float parameter in range [q_min, q_max]"""
# Clean and format input string
binary = clean_binary_string(binary, 7) # 7 bits for parameters
try:
val = int(binary, 2) / 25.5 * 10 # conversion to 0.0 - 10.0 float
# Scale to range [q_min, q_max]
q = q_min + ((q_max - q_min) / (2**len(binary))) * val
return q
except ValueError as e:
print(f"Error in bin_to_param with input: '{binary}'")
raise e