![]() |
How to convert binary data into text? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to convert binary data into text? (/thread-34292.html) |
How to convert binary data into text? - ZYSIA - Jul-16-2021 hi this is my coding to convert HEX to Binary : # conversion of hex string # to binary string import math # Initialising hex string ini_string = "6EDAC" # Printing initial string print ("Initial string", ini_string) # Code to convert hex to binary res = "{0:08b}".format(int(ini_string, 16)) # Print the resultant string print ("Resultant string", str(res))and the results I've got is 1101110110110101100 in binary, i would like to covert them into text in python, like a text "1101110110110101100" so that i can assign each and give every single one of them a declaration like this binary position 19 = 0.5 binary position 18 = 0.25 ... etc in the end i want to do a simple check and add function : if binary 19 = 1, binary 18 =1, 0.5 + 0.25 etc.. the results will be something like 0.0011. anyone got an idea how to convert or assign each binary position a value? appreciate your help here :) RE: How to convert binary data into text? - Larz60+ - Jul-16-2021 try: # conversion of hex string # to binary string import math # Initialising hex string ini_string = "6EDAC" res = bin(int(ini_string, 16))[2:].zfill(8) print(res, type(res)) # each bit can be addressed like res[0], res[6], etc. print(res[0]) print(res[6])this gives:
RE: How to convert binary data into text? - DeaD_EyE - Jul-16-2021 String-formatting could help. important_value = 42 print(f"{important_value:08b}") print(f"{important_value:016b}") print(f"{important_value:024b}") print(f"{important_value:032b}") Quote:00101010 RE: How to convert binary data into text? - deanhystad - Jul-16-2021 Does this do what you want? # weight for bit 0, 1, ... 7 weights = [0.1, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2] number = 0x2C # Convert number to binary '0b101100', remove '0b' and reverse order of bits to '001101' bits = bin(number)[:1:-1] # If bit is set, put corresponding weight in values list, else 0 values = [weight if bit=='1' else 0 for weight, bit in zip(weights, bits)] print(values, sum(values))You can replace the string conversion stuff with math values = [] for weight in weights: values.append(weight * number % 2) number = number // 2 print(values, sum(values)) |