0

I often need to convert status code to bit representation in order to determine what error/status are active on analyzers using plain-text or binary communication protocol.

I use python to poll data and to parse it. Sometime I really get confuse because I found that there is so many ways to solve a problem. Today I had to convert a string where each character is an hexadecimal digit to its binary representation. That is, each hexadecimal character must be converted into 4 bits, where the MSB start from left. Note: I need a char by char conversion, and leading zero.

I managed to build these following function which does the trick in a quasi one-liner fashion.

def convertStatus(s, base=16):
    n = int(math.log2(base))
    b = "".join(["{{:0>{}b}}".format(n).format(int(x, base)) for x in s])
    return b

Eg., this convert the following input:

0123456789abcdef

into:

0000000100100011010001010110011110001001101010111100110111101111

Which was my goal.

Now, I am wondering what another elegant solutions could I have used to reach my goal? I also would like to better understand what are advantages and drawbacks among solutions. The function signature can be changed, but usually it is a string for input and output. Lets become imaginative...

jlandercy
  • 7,183
  • 1
  • 39
  • 57

1 Answers1

0

This is simple in two steps

  1. Converting a string to an int is almost trivial: use int(aString, base=...)
    • the first parameter is can be a string!
    • and with base, almost every option is possible
  2. Converting a number to a string is easy with format() and the mini print language

So converting hex-strings to binary can be done as

def h2b(x):
    val = int(x, base=16)
    return format(val, 'b') 

Here the two steps are explicitly. Possible it's better to do it in one line, or even in-line

Albert
  • 627
  • 6
  • 8
  • Good answer. This is the pythonic way to do it because its simple and straighforward. Could return format(val, 'b').zfill(len(x) * 4) if needed. –  Sep 03 '15 at 21:03
  • You can nest format specifiers. Thus, the formatting can be done in one method call. `"{:0{}b}".format(val, num_chars)`. This you can make the base variable. – Dunes Sep 03 '15 at 21:36