2

Both binascii.(un)hexlify() and .en(de)code("hex") seem to convert between a string representation of a hex value for a string, an the string itself. The only difference I see is that one requires importing the binascii module.

I'm really new to using hex representations, so I'd like to ask if these are really equivalent or is there something deeper I'm not aware of.

Both of the following happen to return True, but that doesn't mean they are always equivalent.

'hello'.encode("hex")      == binascii.hexlify('hello')         # either returns '68656c6c6f'

'68656c6c6f'.decode("hex") == binascii.unhexlify('68656c6c6f')  # either returns 'hello'

edit: based on @sideshowbarker's comment, this answer says:

In Python 3 you can't call encode() on 8-bit strings anymore, so the hex codec became pointless and was removed.

Are these still equivalent in Python-2.7? I don't actually know how to generate a 7-bit vs 8-bit string, so I'm not sure how to test this myself.

uhoh
  • 3,713
  • 6
  • 42
  • 95
  • 2
    https://stackoverflow.com/questions/13435922/python-encode/13437894#13437894 seems relevant – sideshowbarker May 07 '18 at 08:26
  • 1
    8-bit strings is just `bytes`. In Python 2, it is `str` type. In Python 3, it is `bytes` type. There is no `bytes.encode` method in Python 3. You can use `codecs.encode(b'hello', 'hex')` or `b'hello'.hex()` in Python 3. – jfs May 18 '18 at 10:30
  • @jfs I have a hunch your comment is insightful and very helpful. I'll give it a look in the morning. I spend 99% of my time with floats and arrays, so this is all new to me. Thanks! – uhoh May 18 '18 at 12:21

0 Answers0