Python Forum

Full Version: How to convert binary data into text?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 :)
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:
Output:
1101110110110101100 <class 'str'> 1 0
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
0000000000101010
000000000000000000101010
00000000000000000000000000101010
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))