I have been playing around with the codecs
module lately and I stumbled upon this behavior that I find rather weird:
codecs.encode(b'a', 'hex')
returns b'61'
.
My question is, why? I really didn't expect it to return b'61'
. I was expecting b'\x61'
.
The former is a bytes
object with length 2 (len(b'61') == 2
), whereas the latter one is a bytes
object with length 1 (len(b'\x61') == 1
).
I didn't expect this behavior at all, because b'a'
, which is supposed to be 1-byte, has became 2-bytes when encoded with the 'hex'
codecs.
What would you have done to convert an ASCII character to its hex-encoded bytes
representation? What I did was:
codecs.decode(hex(ord('a'))[2:], 'hex')
But I felt like this is kind of a dirty hack.