1

I'm trying an example almost straight out of the version 2.5.2 documentation for the Python Library Reference for the function "a2b_base64()" which is part of the "binascii" module. I am trying to convert a hex number to its binary value. Eventually I need to convert a whole hex file to binary.

The function is techniclly for a string, but the error I'm getting says "NameError : name 'a2b_base64' is not defined". Any idea why this fails? I wish I could use a more mordern version of Python and avoid the a2b_base64() function, but can't. Thanks.

import binascii
num = a2b_base64("04") 
print num
user2994541
  • 45
  • 1
  • 1
  • 5

1 Answers1

1

In Python, each module has its own namespace. By default, you need to include the module name when calling a method in that module:

import binascii
num = binascii.a2b_base64("04")
print num

Note that a2b_base64 converts a string of Base64-encoded binary data into its raw binary form, which sounds like it's not what you actually want. To convert a string of hexadecimal digits into a string of hex data, use a2b_hex:

>>> import binascii
>>> binascii.a2b_hex("04")
'\x04'
Tim Pierce
  • 5,514
  • 1
  • 15
  • 31
  • Thanks for the module.method point out. Both examples give unexpected results (to me). The last returned a diamond shape character, the first gives an "incorrect padding error". I tried adding some leading zeros. At three, I finally got no error, but the returned result was a "u" with subscript "m8". – user2994541 Nov 25 '13 at 18:01
  • The `a2b_base64` function doesn't have anything to do with converting hex to binary. I'm almost certain that's not going to help you with whatever you're trying to do. If you want to read a hex string and get the integer it represents, use the `int` function: e.g. `int("1A", 16)`. – Tim Pierce Nov 25 '13 at 18:28
  • Thanks for the insight and your patients with the newbie questions. Is there some off the shelf command or function to convert an int to binary? With the old version 2.5.2, which I'm stuck with, it looks like there is little support for doing this. – user2994541 Nov 25 '13 at 19:03
  • Can you clarify about what you mean by "to binary"? `binascii.a2b_hex("04")` will produce a string containing binary data that's represented by the hex digits "04", i.e. a string of one byte in which bit #3 is set. If what you mean is that you want to transform the string of hex characters "04" into a string of zero and one characters like "0100", there are some helpful answers at http://stackoverflow.com/questions/699866/python-int-to-binary. Some of them require more recent versions of Python than what's available to you but they may help get you closer to an answer. – Tim Pierce Nov 25 '13 at 19:58