TimSandiego Hollister
TimSandiego Hollister

Reputation: 115

hex to bin converted and print in multiple rows

I am hardcoding the following function to decode hex to binanry. it does not look elegant as I want to be but it works. Can someone help me to generalize the code?

def print_hex_to_atp(hex,output_file):  

    if hex=="0":
        output_file.write("> Data   0 end;\n") #print hex 0 in binary
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   0 end;\n")
    elif hex=="1":
        output_file.write("> Data   0 end;\n") #print hex 1 in binary
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   1 end;\n")
    elif hex=="2":
        output_file.write("> Data   0 end;\n") #print hex 2 in binary
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   1 end;\n") 
        output_file.write("> Data   0 end;\n")
    elif hex=="3":
        output_file.write("> Data   0 end;\n") #print hex 3 in binary
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   1 end;\n") 
        output_file.write("> Data   1 end;\n")
    elif hex=="4":
        output_file.write("> Data   0 end;\n") #print hex 4 in binary
        output_file.write("> Data   1 end;\n") 
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   0 end;\n")
    elif hex=="5":
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   1 end;\n")
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   1 end;\n")
    elif hex=="6":
        output_file.write("> Data   0 end;\n") 
        output_file.write("> Data   1 end;\n") 
        output_file.write("> Data   1 end;\n") 
        output_file.write("> Data   0 end;\n")

    else:
        c="invalid"

Upvotes: 0

Views: 113

Answers (3)

Izaak van Dongen
Izaak van Dongen

Reputation: 2545

You can use the bin function and the base argument of int:

def hex_to_bin(h):
    return bin(int(h, 16))[2:]

example = "1a"

for binary_digit in hex_to_bin(example):
    print(binary_digit)

This has the output:

1
1
0
1
0

Note that this will throw a ValueError if you pass it an invalid hex string.

If you want it to be padded to the nearest nibble, you can do:

def hex_to_bin(h):
    return "{:0{}b}".format(int(h, 16), len(h) * 4)

which will have the output:

0
0
0
1
1
0
1
0

As demonstrated, both of these work on arbitrary length hex strings, not just single digits.

Both of these work by first parsing the hex-string into an integer, using the int function, and then formatting that integer as binary. The second uses Python's format mini-language, specifying that the format (:) should be in binary (b), padded with zeroes (0), and it should be four times the length of the hex-string ({} -> len(h) * 4). The {} curly braces are used to indicate arguments given to format. The first uses the bin function, which is self-explanatory enough, but it has to do [2:] as the bin function adds 0b to the start of the generated binary. 2: slices that away.

It should be easy enough to reimplement into your original code. To do so, you would do something like this:

for digit in hex_to_bin(hex_s):
    output_file.write("> Data   {} end;\n".format(digit))

Note that I've renamed your variable hex. I'd recommend you do the same, as hex is a builtin Python function (this might get especially confusing if you plan to be working with hex).

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113948

hex="4"
base_10 = int(hex,16)
bin = "{0:04b}".format(base_10)
print("0x{0:02x} -> 0b{0:04b}".format(base_10) )
for bit in bin:
    print("> data\t{0} end".format(bit))

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

You can use int(..,16) to decode hexadecimal string into an integer. Furthermore you can for instance use a for loop to obtain the four different bits, like:

def print_hex_to_atp(hex,output_file):
    try:
        data = int(hex,16)
        if data < 16:
            for i in range(3,-1,-1):
                output_file.write("> Data   {} end;\n".format((data>>i) & 1))
        else:
            # do something in case the value is greater than 15
            pass
    except ValueError:
        # do something in case hex is not a valid hexadecimal string
        pass

Upvotes: 0

Related Questions